代码之家  ›  专栏  ›  技术社区  ›  ryanprayogo

Java正则表达式混乱

  •  2
  • ryanprayogo  · 技术社区  · 14 年前

    我有以下(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 回复  |  直到 14 年前
        1
  •  3
  •   jjnguy Julien Chastang    14 年前

    这是因为 . .* . 所以,当你打电话的时候 matches()

    第二个返回true,因为它在输入字符串中找到匹配项。它不一定匹配整个字符串。

    the Pattern javadocs :

    . 任何字符(可能与行终止符匹配,也可能不匹配)

        2
  •  1
  •   Andre Holzner    14 年前

    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() 好像它包围了你的regexp ^ $ 以确保字符串的开头与正则表达式的开头匹配,并且字符串的结尾与正则表达式的结尾匹配。

        3
  •  0
  •   Colin Hebert    14 年前

    匹配模式和在字符串中查找模式是有区别的

    • String.matches()

      指示此字符串是否与给定的正则表达式匹配。

      你的整根绳子必须和图案匹配。

    • Matcher.matches() :

      再说一遍,你的整个弦必须匹配。

    • Matcher.find()

      尝试查找与模式匹配的输入序列的下一个子序列。

      这里你只需要一个“部分匹配”。


    正如@Justin所说:
    matches() 不能当警察 . 不匹配新行字符( \n \r \r\n


    资源: