2010-09-08 53 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)。


资源: