gpt4 book ai didi

java - 将正则表达式匹配回同一行的开头?

转载 作者:行者123 更新时间:2023-11-30 11:25:11 28 4
gpt4 key购买 nike

给定:

-- 输入--

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:”,从该行开头以及之后的所有内容都会被压缩(删除)?

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

最佳答案

这是一种方法,a demonstration on ideaone .

我稍微简化了模式;然而,我的代码中最大的变化是它在没有 DOTALL 选项的情况下运行 - 使用 DOTALL . 将错误地匹配 多行。

^(.*)chomp:(.*)

模式应该匹配一次(这似乎是意图),用“chomp:”之前/之后的文本填充组 12 以及其余数据将被“消耗”,因为它只是未处理。要在正则表达式匹配(而不是匹配)之前获取数据,我使用以下结构:

StringBuffer sb = new StringBuffer();
matcher.appendReplacement(sb, "");

(虽然这可以用子字符串替换,但我想,这个成语 mirrors other patterns 。)


如果您希望进行面向行的处理(适合大流),那么正确的做法是依次处理每一行。我自己可能会使用拆分或扫描器方法,但我希望将这个答案保留在最初提出的原始整体正则表达式方法中。

例如:

Scanner s = new Scanner(input);
while (s.hasNextLine()) {
// process next line and "break" if it matches the end-line condition
}

ideone 的片段:

String text = "Keep this.\nAnd keep this.\n\nAnd keep this too.\n"
+ "Chomp this chomp:\nAnything beyond here gets chomped.";
Pattern CHOMP= Pattern.compile("^(.*)chomp:(.*)", Pattern.MULTILINE);
Matcher m = CHOMP.matcher(text);
if (m.find()) {
System.out.println(" LINE:" + m.group(0));
System.out.println("BEFORE:" + m.group(1));
System.out.println(" AFTER:" + m.group(2));
System.out.println(">>>");
StringBuffer sb = new StringBuffer();
m.appendReplacement(sb, "");
System.out.print(sb);
System.out.println("<<<");
}

关于java - 将正则表达式匹配回同一行的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20389210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com