在 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/