gpt4 book ai didi

java - 匹配非多行正则表达式

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

我有以下文件内容,我正在尝试匹配下面解释的注册表:

-- file.txt (doesn't match single/in-line text) -- 
test On blah more blah wrote:
blah blah blah
blah blah
blah
---------------

如果我从上面读取文件内容到字符串并尝试匹配“On...wrote:”部分,我无法获得匹配:

    // String text = <file contents from above>
Pattern PATTERN = Pattern.compile("^(On\\s(.+)wrote:)$");
Matcher m = PATTERN.matcher(text);
if (m.find()) {
System.out.println("Never gets HERE???");
// TODO: Strip out all characters after the match and any \s or \n before
}

本质上我想要以下输出:

-- file2.txt -- 
test
---------------

最佳答案

也许这可以帮助您获得您想要的结果:

        String text = "test On blah more blah wrote:\n" 
+ "blah blah blah\nblah blah\nblah\n";
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Pattern PATTERN = Pattern.compile("^(.*?)\\s*On\\s(.+)wrote:$",
Pattern.MULTILINE);
Matcher m = PATTERN.matcher(text);
if (m.find()) {
pw.println(m.group(1));
}
pw.close();
System.out.println(sw);

Pattern.MULTILINE javadoc:在多行模式下,表达式 ^ 和 $ 分别匹配行终止符之后或之前 ...我还添加了 (.*?) 来匹配所有内容在第一个“On”之前。

关于java - 匹配非多行正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198804/

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