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

关于一个奇怪的Java正则表达式行为的问题

  •  0
  • Sapience  · 技术社区  · 14 年前

    "^[\\.\\d]+"
    

    下面是我的代码:

    public void testMiscellaneous() throws Exception {
        System.out.println("~~~~~~~~~~~~~~~~~~~testMiscellaneous~~~~~~~~~~~~~~~~~~~~");
        String s1 = ".123 *[DP7_Dog]";
        String s2 = ".123";
        String s3 = "1.12.3";
        String s4 = "a1.12.3";
        final String numberRegex = "^[\\.\\d]+";
        System.out.println(s1.matches(numberRegex));
        System.out.println(s2.matches(numberRegex));
        System.out.println(s3.matches(numberRegex));
        System.out.println(s4.matches(numberRegex));
    }
    

    输出为

    false
    true
    true
    false
    

    1 回复  |  直到 14 年前
        1
  •  2
  •   Carl Smotricz    14 年前

    问题是 matches() 坚持匹配整个输入字符串,就像 ^ $ 最后。

    Matcher.find() Matcher.lookingAt() .* 在你的模式结束时。