I want to test whether a regexp is valid in Java 1.8.0_241
public static boolean isRegExpValid(String regExp) {
try {
Pattern.compile(regExp);
return true;
} catch (PatternSyntaxException e) {
return false;
}
}
Here I am testing a correct regexp for a three digit number, and an incorrect regexp.
@Test
public void testValidRegexp() {
assertTrue(isRegExpValid("\\d{3}"));
}
@Test
public void testInvalidRegexp() {
assertFalse(isRegExpValid("{3}"));
}
Why is my second test testInvalidRegexp
failing? isRegExpValid("{3}")
should return false, but returns true.
In Javascript, {3}
correctly fails with a Nothing to repeat exception.
It appears to successfully match the empty string:
jshell> Pattern.matches("{3}x", "x")
$1 ==> true
The documentation doesn't appear to define this as a valid use, but it passes where other minor syntax problems would be detected and throw Pattern.error
.
To analyse why the implementation accepts this, you'd want to figure out where Pattern#closure
can be called from while parsing a pattern.