我有一个正则表列表,我想从中提取那些相当于字符串比较的正则表达式.
例如,那些正则表达式相当于一个简单的字符串比较:
[r"example", # No metacharacters
r"foo\.bar"] # . is not a metacharacter because it is escaped
Run Code Online (Sandbox Code Playgroud)
而那些正则表达式不是:
[r"e.ample", # . is a metacharacter
r"foo\\.bar"] # . is a metacharacter because it is not escaped
Run Code Online (Sandbox Code Playgroud)
根据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"))
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |