我有一个正则表达式列表,我想从中提取与字符串比较等价的正则表达式。
例如,这些正则表达式等价于一个简单的字符串比较:
[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对象或其他什么的快捷方式。
发布于 2016-02-23 16:01:09
受Keith评论的启发,这里有一个基于Python regex编译器的无文档特性的解决方案:
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发布于 2016-02-23 20:05:24
下面是一个正则表达式,可以用来检测python中的非转义元字符:
>>> rex = re.compile(r'^([^\\]*)(\\.[^.^$*+?{}\[\]|()\\]*)*[.^$*+?{}\[\]|()]',re.MULTILINE)
>>> arr = [r"example", r"foo\.bar", r"e.ample", r"foo\\.bar", r"foo\\bar\.baz"]
>>> for s in arr:
... print s, re.search(rex, s) != None
...上面的regex使用\扫描输入的任何转义,然后忽略\旁边的字符。最后,它搜索一个元字符,该元字符是:
. ^ $ * + ? { } [ ] | ( ) \ ]没有前面的\的字符。
输出:
example False
foo\.bar False
e.ample True
foo\\.bar True
foo\\bar\.baz FalseCode Demo
https://stackoverflow.com/questions/35580689
复制相似问题