如何发现正则表达式是否包含非转义元字符?

2024-06-26 10:09:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正则表达式列表,我想从中提取那些等价于字符串比较的正则表达式。你知道吗

例如,这些regex相当于一个简单的字符串比较:

[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对象之类的东西的快捷方式。你知道吗


Tags: no字符串列表fooisexamplenotbar
2条回答

下面是一个正则表达式,可用于在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 False

Code Demo

受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

相关问题 更多 >