2010-09-08 49 views
2

我有以下的(Java)的代碼:Java的正則表達式混亂

public class TestBlah { 
    private static final String PATTERN = ".*\\$\\{[.a-zA-Z0-9]+\\}.*"; 

    public static void main(String[] s) throws IOException { 
     String st = "foo ${bar}\n"; 

     System.out.println(st.matches(PATTERN)); 
     System.out.println(Pattern.compile(PATTERN).matcher(st).find()); 
     System.exit(0); 
    } 
} 

運行這段代碼,前者System.out.println輸出false,而後者輸出true

難道我不是在這裏瞭解些什麼呢?

回答

3

這是因爲.將不匹配新的行字符。因此,包含新行的字符串將與以.*結尾的字符串不匹配。所以,當您撥打matches()時,它會返回false,因爲新行不匹配。

第二個返回true,因爲它在輸入字符串中找到匹配項。它不一定匹配整個字符串。

the Pattern javadocs

.任何字符(可能或可能不匹配行終止)

+1

從同一個文檔:正則表達式。匹配除行結束符之外的任何字符,除非指定了DOTALL標誌。 – gawi 2010-09-08 20:31:43

1

String.matches(..)行爲就像Matcher.matches(..)。從Matcher

find(): Attempts to find the next subsequence of 
     the input sequence that matches the pattern. 

matches(): Attempts to match the entire input sequence 
     against the pattern. 

的文檔,以便你能想到的matches(),如果它環繞你的正則表達式與^$以確保字符串的開頭你的正則表達式的開頭和字符串匹配的結尾匹配正則表達式的結尾。

0

有匹配的圖案,並在字符串

  • String.matches()找到圖案之間的差:

    通知此串是否給定正則表達式匹配。

    您的整個字符串必須匹配該模式。

  • Matcher.matches()

    嘗試來匹配圖案中的整個輸入序列。

    再次您的整個字符串必須匹配。

  • Matcher.find()

    試圖找到該模式匹配的輸入序列的下一個子。

    在這裏你只需要一個「部分匹配」。


正如@Justin說:
matches()不能作爲.工作將不匹配換行符(\n\r\r\n)。


資源: