2013-10-08 121 views
4

正則表達式我有以下的文件內容,我試圖匹配一個reg說明如下:匹配的多不工作

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

On blah 

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

如果我從上面讀取文件內容爲一個字符串,並嘗試符合「關於...寫道:」部分我不能讓比賽:

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

如何讓多行工作和單行都在一個正則表達式中(或兩個)?謝謝!

回答

3

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

添加Pattern.DOTALL標誌以允許點.字符與換行符匹配。這是使用bitwise inclusive OR|操作

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

太棒了!廣告第一次工作!謝謝! – JaJ

+0

沒問題,很高興幫助! :) – Reimeus

1

你可以使用匹配\S非空白)和\s

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

組合(空白)查看live regex101 demo

例如:

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