You can just Pattern.compile
the regex string and see if it throws PatternSyntaxException
.
String regex = "***";
PatternSyntaxException exc = null;
try {
Pattern.compile(regex);
} catch (PatternSyntaxException e) {
exc = e;
}
if (exc != null) {
exc.printStackTrace();
} else {
System.out.println("Regex ok!");
}
This one in particular produces the following output:
java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
***
^
Regarding lookbehinds
Here's a quote from the old trusty regular-expressions.info:
Important Notes About Lookbehind
Java takes things a step further by allowing finite repetition. You still cannot use the star or plus, but you can use the question mark and the curly braces with the max parameter specified. Java recognizes the fact that finite repetition can be rewritten as an alternation of strings with different, but fixed lengths.
I think the phrase contains a typo, and should probably say "different, but finite lengths". In any case, Java does seem to allow alternation of different lengths in lookbehind.
System.out.println(
java.util.Arrays.toString(
"abracadabra".split("(?<=a|ab)")
)
); // prints "[a, b, ra, ca, da, b, ra]"
There's also a bug in which you can actually have an infinite length lookbehind and have it work, but I wouldn't rely on such behaviors.
System.out.println(
"1234".replaceAll(".(?<=(^.*))", "$1!")
); // prints "1!12!123!1234!"