2013-04-11 51 views
2

任何人都可以幫助正則表達式嗎?此代碼工作良好。Java正則表達式。奇怪的行爲

public static void main(String[] args) { 

    String s = "with name=successfully already exist\n"; 

    Pattern p = Pattern.compile(".+name=.*successfully.+", Pattern.DOTALL); 
    java.util.regex.Matcher m = p.matcher(s); 

    if (m.matches()) { 
     System.out.println("match"); 
    } else { 
     System.out.println("not match"); 
    } 

} 

但此代碼返回「不匹配」。爲什麼?

public static void main(String[] args) { 

    String s = "with name=successfully already exist\n"; 

    if (s.matches(".+name=.*successfully.+")) { 
     System.out.println("match"); 
    } else { 
     System.out.println("not match"); 
    } 

} 

回答

5

兩者之間的唯一區別是第一個示例中的DOTALL標誌。

沒有該標誌,字符串末尾的\n將與最後一個模式(.+)不匹配。

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL

在DOTALL模式下,表達式。匹配任何字符,包括行結束符。默認情況下,該表達式不匹配行結束符。

注意matches試圖將整個字符串匹配(包括在你的情況下,尾隨的換行符),而不只是試圖找到一個字符串(這是在Java中比許多其他語言不同)。

4

使用compile()時提供的Pattern.DOTALL參數使得'。'匹配'行結束符'。你需要提供一個內聯標籤來匹配()。請嘗試以下操作:

s.matches("(?s).+name=.*successfully(?s).+") 

乾杯。