且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-26 11:26:06

类似于 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.