How to determine if a regular expression contains unexperimentated metacharacters?

I have a list of regular expressions from which I want to extract those that are equivalent to string comparisons.

For example, these regular expressions are equivalent to simply matching strings:

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

while these regular expressions are not:

[r"e.ample",   # . is a metacharacter
 r"foo\\.bar"] # . is a metacharacter because it is not escaped

According to https://docs.python.org/2/howto/regex.html , a list of valid metacharacters is . ^ $ * + ? { } [ ] \ | ( ).

I am going to create a regex, but it looks a little more complicated. I am wondering if there is a shortcut when exploring an object reor something like that.

+4
source share
2 answers

, , 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
+6

, 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
...

\, , \. , , :

. ^ $ * + ? { } [ ] | ( ) \ ]

\.

:

example False
foo\.bar False
e.ample True
foo\\.bar True
foo\\bar\.baz False

+2

Source: https://habr.com/ru/post/1630080/


All Articles