如何检查字符串是否是正则表达式 [英] How to check if the string is a regular expression or not
问题描述
我有一个字符串。我如何检查字符串是正则表达式还是包含正则表达式或者是普通字符串?
I have a string. How I can check if the string is a regular expression or contains regular expression or it is a normal string?
推荐答案
唯一可靠的如果 String
是一个语法正确的正则表达式,请检查:
The only reliable check you could do is if the String
is a syntactically correct regular expression:
boolean isRegex;
try {
Pattern.compile(input);
isRegex = true;
} catch (PatternSyntaxException e) {
isRegex = false;
}
但请注意,这将导致为真
即使是像 Hello World
和这样的字符串,我也不是正则表达式
,因为从技术上来说是有效的正则表达式。
Note, however, that this will result in true
even for strings like Hello World
and I'm not a regex
, because technically they are valid regular expressions.
这将返回 false
的唯一情况是无效正则表达式的字符串,例如 [未关闭字符类
或(未关闭组
或 +
。
The only cases where this will return false
are strings that are not valid regular expressions, such as [unclosed character class
or (unclosed group
or +
.
这篇关于如何检查字符串是否是正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!