在 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/