【发布时间】:2013-11-30 00:42:03
【问题描述】:
我正在尝试找出一个支持以下 2 个用例的正则表达式:
用例 1:
-- File 1 (input) --
keepthis
junkhere:
this should be removed
用例 2:
-- File 2 (input) --
keepthis
------------
junkhere:
this should be removed
基本上,我正在构建一个正则表达式来删除“junkhere:”中的所有内容。但是,在用例 2 中有一个可选的“------------”,它有时会包含在“junkhere:”之前的行中,但并非总是如此(不确定 - 的确切含义) .
输出应该是:
-- File 3 (output) --
keepthis
我有以下正则表达式,它适用于用例 1,但不适用于用例 2:
Pattern JUNKHERE_REGEX = Pattern.compile("^(((-+)(.*))?junkhere:(.*))$", Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = JUNKHERE_REGEX.matcher(<input from either file1 or file2>);
if (m.find()) || (n.find() || (o.find()) { // there could be other matchers here n and o in this case so I would like to keep the replaceall code below the same so I don't have to create a new if statement
text = m.replaceAll("");
text = text.replaceAll("[\n]+$", ""); // replace and delete any newlines
}
System.out.println(text); // should echo "keepthis"
我对正则表达式不太擅长,但我需要什么才能使它适用于用例 2(和用例 1)?
谢谢!
【问题讨论】:
-
你能不能用上面的代码做一个SSCCE,它甚至无法编译。
-
我假设您在正则表达式模式后不小心遗漏了双引号...
-
您提供的内容适用于用户案例 2 和 1.. 检查此链接 regexr.com?37eea