我想要以下内容:
-输入-
keep this
keep this too
------ Remove Below ------
remove all of this
成为:
-输出-
keep this
keep this too
但是,我无法弄清楚如何匹配所有内容,直到“ ------在...下删除–----”为止,以便我可以对事物进行分组并删除除上述预期输出以外的所有内容。
String text = "keep this\n \n"
+ " keep this too\n ------ Remove Below ------\n remove all of this\n";
Pattern PATTERN = Pattern.compile("^(.*)(-+)(.*)Remove Below(.*)(-+)(.*)$",
Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = PATTERN.matcher(text);
if (m.find()) {
int count = m.groupCount();
String g0 = m.group(0);
String g1 = m.group(1); // contains "keep this\n \n keep this too\n -----"
String g2 = m.group(2);
//
// How can I group correctly to arrive at above expected -- Output --??
//
}
使您的正则表达式non-greedy
:
Pattern PATTERN = Pattern.compile("^(.*?)(-+)(.*?)Remove Below(.*?)(-+)(.*)$",
Pattern.DOTALL);
也Pattern.MULTILINE
没有必要在你的情况。
现在m.group(1)
将给您:
keep this\n \n keep this too\n
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句