我有一个正则表达式列表,从中提取那些与字符串比较等价的对象。
例如,这些正则表达式相当于一个简单的字符串比较:

[r"example",   # No metacharacters
 r"foo\.bar"]  # . is not a metacharacter because it is escaped

而这些正则表达式不是:
[r"e.ample",   # . is a metacharacter
 r"foo\\.bar"] # . is a metacharacter because it is not escaped

根据https://docs.python.org/2/howto/regex.html,有效元字符的列表是. ^ $ * + ? { } [ ] \ | ( )
我要建立一个正则表达式,但它看起来有点复杂。我想知道是否有捷径通过检查re对象或什么。

最佳答案

受Keith Hall评论的启发,这里有一个基于Python正则表达式编译器的未记录特性的解决方案:

import re, sys, io

def contains_meta(regex):
    stdout = sys.stdout            # remember stdout
    sys.stdout = io.StringIO()     # redirect stdout to string
    re.compile(regex, re.DEBUG)    # compile the regex for the debug tree side effect
    output = sys.stdout.getvalue() # get that debug tree
    sys.stdout = stdout            # restore stdout
    return not all(line.startswith("LITERAL ") for line in output.strip().split("\n"))

输出:
In [9]: contains_meta(r"example")
Out[9]: False

In [10]: contains_meta(r"ex.mple")
Out[10]: True

In [11]: contains_meta(r"ex\.mple")
Out[11]: False

In [12]: contains_meta(r"ex\\.mple")
Out[12]: True

In [13]: contains_meta(r"ex[.]mple")  # single-character charclass --> literal
Out[13]: False

In [14]: contains_meta(r"ex[a-z]mple")
Out[14]: True

In [15]: contains_meta(r"ex[.,]mple")
Out[15]: True

10-04 22:22
查看更多