簡體   English   中英

匹配多行上的正則表達式不起作用

[英]Matching a regular expression on multiline not working

我有以下文件內容,我正在嘗試匹配下面解釋的reg:

-- file.txt (doesn't match multi-line) -- 
test

On blah

more blah wrote:
---------------

如果我從上面讀取文件內容到String並嘗試匹配“On ... write:”部分我無法得到匹配:

    // String text = <file contents from above>
    Pattern PATTERN = Pattern.compile("^(On\\s(.+)wrote:)$", Pattern.MULTILINE);
    Matcher m = PATTERN.matcher(text);
    if (m.find()) {
       System.out.println("Never gets HERE???");
    }

如果文件的內容在一行,上面的正則表達式工作正常:

-- file2.txt (matches on single line) -- 
test

On blah more blah wrote: On blah more blah wrote:
---------------

如何在一個正則表達式中使用多行(單行)和單行(或兩個)? 謝謝!

Pattern.MULTILINE只是告訴Java接受錨點^$匹配每行的開頭和結尾。

添加Pattern.DOTALL標志以允許點. 用於匹配換行符的字符。 這是使用按位包含OR | 操作者

Pattern PATTERN = 
    Pattern.compile("^(On\\s(.+)wrote:)$", Pattern.MULTILINE | Pattern.DOTALL );

您可以使用匹配\\S非空白 )和\\s空白 )的組合

Pattern PATTERN = Pattern.compile("(On\\s([\\S\\s]*?)wrote:)");

查看live regex101演示

例:

import java.util.regex.*;

class rTest {
  public static void main (String[] args) {
    String s = "test\n\n"
             + "On blah\n\n"
             + "more blah wrote:\n";
    Pattern p = Pattern.compile("(On\\s([\\S\\s]*?)wrote:)");
    Matcher m = p.matcher(s);
    if (m.find()) {
      System.out.println(m.group(2));
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM