【问题标题】:Strip paragraph text before cue word在提示词之前去除段落文本
【发布时间】:2020-07-30 19:46:29
【问题描述】:

我有这样的文字:

Last login: today


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

我需要像这样检索信息:

testMachine:root:/root# cat file
File contents

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

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

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

【问题讨论】:

  • 您可以使用paragraph.indexOf(cueword) 找出cuewordparagraph 中的第一次出现。然后使用substring
  • 正如我所说,我已经这样做了,但它不起作用。结果与删除提示词相同。

标签: javascript java rhino nashorn


【解决方案1】:

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"))

【讨论】:

  • 一方面,这在我运行脚本时按预期工作。另一方面,它不适用于我的应用程序。我必须在 JS for Java 引擎上使用它,我认为这将是相同的结果......显然不是。 Nashorn 返回错误并且无法运行脚本,Rhino 在我删除 let 运算符后工作。我绝对应该这样标记这个问题,但我不知道这是问题的一部分。感谢您的帮助。
  • 我将此标记为答案,因为问题结果与工具有关,而不是 JS 代码,而且您的答案在技术上是正确的。
猜你喜欢
  • 2014-11-11
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 2019-09-03
  • 2011-10-02
相关资源
最近更新 更多