如何检查字符串是否是正则表达式 [英] How to check if the string is a regular expression or not

查看:194
本文介绍了如何检查字符串是否是正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串。我如何检查字符串是正则表达式还是包含正则表达式或者是普通字符串?

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆