在 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?
}
除了标有注释的两行外,每一行都通过。除了模式字符串之外,这些分组是相同的。为什么添加不区分大小写会破坏匹配器?