您唯一可以做的可靠检查是,如果
String语法正确的是正则表达式:
boolean isRegex;try { Pattern.compile(input); isRegex = true;} catch (PatternSyntaxException e) { isRegex = false;}但是请注意,
true即使对于像
Hello World和这样的字符串,也会导致这种情况
I'm not aregex,因为从技术上讲,它们是有效的正则表达式。
唯一会返回的
false情况是不是有效正则表达式的字符串,例如
[unclosed character class或
(unclosedgroup或
+。



