Java RegEx 前瞻失败

标签 java regex regex-lookarounds

在 Java 中,我无法让正则表达式按照我想要的方式运行,因此编写了这个小 JUnit 测试来演示该问题:

public void testLookahead() throws Exception {
    Pattern p = Pattern.compile("ABC(?!!)");
    assertTrue(p.matcher("ABC").find());
    assertTrue(p.matcher("ABCx").find());
    assertFalse(p.matcher("ABC!").find());
    assertFalse(p.matcher("ABC!x").find());
    assertFalse(p.matcher("blah/ABC!/blah").find());

    p = Pattern.compile("[A-Z]{3}(?!!)");
    assertTrue(p.matcher("ABC").find());
    assertTrue(p.matcher("ABCx").find());
    assertFalse(p.matcher("ABC!").find());
    assertFalse(p.matcher("ABC!x").find());
    assertFalse(p.matcher("blah/ABC!/blah").find());

    p = Pattern.compile("[A-Z]{3}(?!!)", Pattern.CASE_INSENSITIVE);
    assertTrue(p.matcher("ABC").find());
    assertTrue(p.matcher("ABCx").find());
    assertFalse(p.matcher("ABC!").find());
    assertFalse(p.matcher("ABC!x").find());
    assertFalse(p.matcher("blah/ABC!/blah").find()); //fails, why?

    p = Pattern.compile("[A-Za-z]{3}(?!!)");
    assertTrue(p.matcher("ABC").find());
    assertTrue(p.matcher("ABCx").find());
    assertFalse(p.matcher("ABC!").find());
    assertFalse(p.matcher("ABC!x").find());
    assertFalse(p.matcher("blah/ABC!/blah").find());  //fails, why?
}

除了标有注释的两行之外,每一行都通过。除了模式字符串之外,分组是相同的。为什么添加不区分大小写会破坏匹配器?

最佳答案

您的测试失败,因为在这两种情况下,模式 [A-Z]{3}(?!!) (带有 CASE_INSENSITIVE)和 [A- Za-z]{3}(?!!)"blah/ABC!/blah" 中至少找到一个匹配项(他们找到 bla 两次) .

简单的测试表明了这一点:

Pattern p = Pattern.compile("[A-Z]{3}(?!!)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("blah/ABC!/blah");
while(m.find()) {
    System.out.println(m.group());
}

打印:

bla
bla

关于Java RegEx 前瞻失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5035500/

相关文章:

java - 如何使用 Action 监听器中设置的变量

java - 递归函数导致 StackOverflowError

java - 无法理解为什么这个 Java 程序会产生这样的输出

java - 将 GET 请求参数获取到 @ViewScoped bean

javascript - 按最顶层括号拆分字符串

Ruby 正则表达式 ‘backslash R’ 又名 ‘\R’ 模式

regex - 编辑电话号码

python - 与标点符号匹配整个字符串(使用\b 的问题)

.net - 如果第一个模式失败,正则表达式会匹配另一个模式

java - 我们可以在 lookbehind 表达式中使用量词吗?