Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 匹配非多行正则表达式_Java_Regex - Fatal编程技术网

Java 匹配非多行正则表达式

Java 匹配非多行正则表达式,java,regex,Java,Regex,我有以下文件内容,我正在尝试匹配下面解释的注册表: -- file.txt (doesn't match single/in-line text) -- test On blah more blah wrote: blah blah blah blah blah blah --------------- 如果我将文件内容从上面读取为字符串,并尝试匹配“On…writed:”部分,则我无法获得匹配: // String text = <file contents from abo

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

-- file.txt (doesn't match single/in-line text) -- 
test On blah more blah wrote:
blah blah blah
blah blah
blah
---------------
如果我将文件内容从上面读取为字符串,并尝试匹配“On…writed:”部分,则我无法获得匹配:

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

由于您要查找的模式没有开始行,请删除
^
。这与一行的开头匹配,但您要查找的行以单词“test”开头


但是,如果要捕获“测试”,请在
^
之后插入
(\\w+)\\s
,以形成
^(\\w+)\\s(在\\s(+)上写:)$

也许这有助于您获得想要的结果:

        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”之前的所有内容。

很酷,感谢您的回复。这正是我想要的…既然我找到了匹配项,在这种情况下,除了“测试”之外,我怎么能替换所有东西呢?我尝试过text=m.replaceAll(“”),但它会替换所有内容。如果您想保留“test”(以及其他不匹配的行),请使用
m.replaceAll($1”)
$1
被扩展到第一个匹配的组。谢谢,所以如果我只是想继续测试,我应该只使用每个m.group(1)返回的内容,还是有一种方法可以合并replaceAll(“通过使用
Pattern.compile”(^(.*)\\s*On\\s(+)写:$.*),Pattern.MULTILINE | Pattern.DOTALL)
如果您愿意,您可以在测试后删除所有行。
模式。DOTALL
使点也与换行符匹配,因此模式末尾的
*
将所有内容都匹配到文本的最后。太棒了!这非常非常有用。所有内容都运行良好。再次感谢!
        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);