如何检查字符串是否是 Python 中的有效正则表达式? [英] How to check if a string is a valid regex in Python?
问题描述
在 Java 中,我可以使用以下函数来检查字符串是否是有效的正则表达式 (来源):
boolean isRegex;尝试 {模式.编译(输入);isRegex = true;} catch (PatternSyntaxException e) {isRegex = false;}
是否有与 Pattern.compile()
和 PatternSyntaxException
等效的 Python?如果是,那是什么?
类似于 Java.使用 re.error
异常:
导入重新尝试:重新编译('[')is_valid = 真除了重新错误:is_valid = 假
<块引用>
异常re.error
当一个字符串传递给这里的函数之一时引发异常不是有效的正则表达式(例如,它可能包含不匹配的括号)或在此期间发生其他错误时编译或匹配.如果字符串不包含任何内容,则永远不会出错匹配模式.
In Java, I could use the following function to check if a string is a valid regex (source):
boolean isRegex;
try {
Pattern.compile(input);
isRegex = true;
} catch (PatternSyntaxException e) {
isRegex = false;
}
Is there a Python equivalent of the Pattern.compile()
and PatternSyntaxException
? If so, what is it?
Similar to Java. Use 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 中的有效正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!