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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19630994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:14:29  来源:igfitidea点击:

How to check if a string is a valid regex in Python?

pythonregexstringvalidation

提问by alvas

In Java, I could use the following function to check if a string is a valid regex (source):

在 Java 中,我可以使用以下函数来检查字符串是否是有效的正则表达式 ( 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?

是否有与Pattern.compile()and等价的 Python PatternSyntaxException?如果是,那是什么?

采纳答案by falsetru

Similar to Java. Use re.errorexception:

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

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.

例外 re.error

当传递给此处函数之一的字符串不是有效的正则表达式(例如,它可能包含不匹配的括号)或在编译或匹配期间发生其他一些错误时引发异常。如果字符串不包含与模式匹配的内容,则永远不会出错。