【发布时间】:2013-12-21 18:09:39
【问题描述】:
给定:
-- 输入--
Keep this.
And keep this.
And keep this too.
Chomp this chomp:
Anything beyond here gets chomped.
-- 输出(预期)--
Keep this.
And keep this.
And keep this too.
如何为每个分组匹配一个正则表达式,以便一旦找到“chomp:”,该行开头和之后的所有内容都会被 chomp(删除)?
String text = "Keep this.\nAnd keep this.\n\nAnd keep this too.\n"
+ "This could be anything here chomp:\nAnything beyond here gets chomped.";
Pattern CHOMP= Pattern.compile("^((.*)chomp:(.*))$", Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = CHOMP.matcher(text);
if (m.find()) {
int count = m.groupCount();
//
// How can I match a group here to either delete or keep for expected output?
//
// text = <match a group to assign or replace non-desired text>;
System.out.println(text); // Should output contents from above -- output (expected) --
}
【问题讨论】: