首页 > 解决方案 > 在提示词之前去除段落文本

问题描述

我有这样的文字:

Last login: today


cat file
testMachine:root:/root# cat file
File contents
testMachine:root:/root#

我需要检索这样的信息:

testMachine:root:/root# cat file
File contents

删除最后一行很容易,但我需要在开始时删除的行数是任意的,我需要删除所有内容,直到第一个提示词,即机器名称,它是已知和存储的。

我已经尝试过substring(),但它逐行删除而不是将整个文本视为一个,并且也删除了主机名,它应该保留在那里。我也试过replace()了,但是我对正则表达式不熟悉,所以结果是内存异常。

编辑 1:似乎很重要的是要注意使用 JS for Java 引擎(在这种情况下,我使用的是 Rhino)意味着结果与您在 web.xml 中获得的结果不同。这是在以下答案后发现的,该答案在网络上完美运行,甚至无法在桌面应用程序上运行。

标签: javascriptjavarhinonashorn

解决方案


const text = ` 
Last login: today


cat file
testMachine:root:/root# cat file
File contents
testMachine:root:/root#`;
const cueWord = "testMachine:root"
const idx = text.indexOf(cueWord);
let restOftheString = text.substring(idx).split("\n");
restOftheString.pop()
console.log(restOftheString.join("\n"))


推荐阅读