为什么我的无效模式没有抛出 PatternSyntaxException?

Jos*_*tos 1 java regex unit-testing patternsyntaxexception

我想测试一个正则表达式在 Java 1.8.0_241 中是否有效

public static boolean isRegExpValid(String regExp) {
    try {
        Pattern.compile(regExp);
        return true;
    } catch (PatternSyntaxException e) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我正在测试三位数的正确正则表达式和不正确的正则表达式。

@Test
public void testValidRegexp() {
    assertTrue(isRegExpValid("\\d{3}"));
}

@Test
public void testInvalidRegexp() {
    assertFalse(isRegExpValid("{3}"));
}
Run Code Online (Sandbox Code Playgroud)

为什么我的第二次测试testInvalidRegexp失败了?isRegExpValid("{3}")应该返回false,但返回true。

在 Javascript 中,{3}正确失败并显示Nothing to repeat异常。 在此处输入图片说明

Joe*_*Joe 6

它似乎成功匹配空字符串:

jshell> Pattern.matches("{3}x", "x")
$1 ==> true
Run Code Online (Sandbox Code Playgroud)

该文档似乎没有将其定义为有效用途,但它通过了其他小的语法问题会被检测到并抛出的地方Pattern.error

要分析实现为何接受这一点,您需要弄清楚Pattern#closure在解析模式时可以从哪里调用。