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

微妙的Java正则表达式

  •  -1
  • Aamir  · 技术社区  · 10 年前
    String str = "1234545";
    String regex = "\\d*";
    
    Pattern p1 = Pattern.compile(regex);
    Matcher m1 = p1.matcher(str);
    
    while (m1.find()) {
    
        System.out.print(m1.group() + " found at index : ");
        System.out.print(m1.start());
    
    }
    

    该程序的输出为 1234545 found at index:0 found at index:7 .

    我的问题是:
    为什么打印了一个空格,而实际上在 str .

    1 回复  |  直到 10 年前
        1
  •  1
  •   Sergey Kalinichenko    10 年前

    打印在 "index:0" "at index:7" 来自您打印的字符串文本。它应该出现在匹配的字符串之后;然而,在这种情况下,匹配是空的。

    下面是发生的情况:第一个匹配将消耗字符串中的所有数字,为接下来的匹配留下零个字符。但是,以下匹配成功,因为星号 * 表达式中允许匹配空字符串。

    为了避免将来出现这种混淆,请在实际匹配项周围添加分隔符,如下所示:

    System.out.print("'" + m1.group() + "' at index : ");
    

    现在您将看到一对空的单引号,显示匹配为空。