gpt4 book ai didi

java - 如何在正则表达式的单行上进行匹配?

转载 作者:行者123 更新时间:2023-12-01 23:11:13 24 4
gpt4 key购买 nike

我有一个正则表达式来匹配一行并将其删除。一切都在它下面(并将一切保持在它上面)。

Two Part Ask:

1) Why won't this pattern match the given String text below?
2) How can I be sure to just match on a single line and not multiple lines?
- The pattern has to be found on the same single line.
    String text = "Keep this.\n\n\nPlease match junkhere this t-h-i-s is missing.\n"
+ "Everything should be deleted here but don't match this on this line" + "\n\n";
Pattern p = Pattern.compile("^(Please(\\s)(match)(\\s)(.*?)\\sthis\\s(.*))$", Pattern.DOTALL );
Matcher m = p.matcher(text);
if (m.find()) {
text = (m.replaceAll("")).replaceAll("[\n]+$", ""); // remove everything below at and below "Please match ... this"
System.out.println(text);
}

预期输出:

Keep this.

最佳答案

你让你的生活变得复杂了......

首先,正如我在评论中所说,使用 Pattern.MULTILINE

然后,要从匹配的开头截断字符串,请使用 .substring():

final Pattern p = Pattern.compile("^Please\\s+match\\b.*?this",
Pattern.MULTILINE);
final Matcher m = p.matcher(input);
return m.find() ? input.substring(0, m.start()) : input;

关于java - 如何在正则表达式的单行上进行匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21944361/

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