python - 如何检查字符串是否是 Python 中的有效正则表达式?

标签 python regex string validation

在 Java 中,我可以使用以下函数来检查字符串是否是有效的正则表达式 (source):

boolean isRegex;
try {
  Pattern.compile(input);
  isRegex = true;
} catch (PatternSyntaxException e) {
  isRegex = false;
}

是否有 Pattern.compile()PatternSyntaxException 的 Python 等效项?如果有,是什么?

最佳答案

类似于 Java。使用re.error异常(exception):

import re

try:
    re.compile('[')
    is_valid = True
except re.error:
    is_valid = False

exception re.error

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern.

关于python - 如何检查字符串是否是 Python 中的有效正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19630994/

相关文章:

python : How do I easily get sub-totals on row and column?

python - Unicode解码错误: 'ascii' codec can't decode byte 0xa3

regex - 使用 sed 将字母 [a-z] 和 [A-Z] 和 ['] 替换为下划线

c# - .NET 正则表达式帮助

python - 在输入文件中查找确切的字符串

java - 将多行文本追加到 JTextArea?

python - 模块如何在 Python 中工作?

Python 类方法和(?)实例方法

c - C 中的正则表达式 (PCRE)

c++ - 我如何创建一个循环,在找到字符串中的特定字符后插入一个字符?