How to check if a given character is a “special” Python regex engine?

Is there an easy way to verify that a given character has a special regular function?

Of course, I can collect regex characters in a type list ['.', "[", "]", etc.]to check this out, but I think there is a more elegant way.

+4
source share
4 answers

You can use re.escape. For instance:

>>> re.escape("a") == "a"
True
>>> re.escape("[") == "["
False

The idea is that if the character is special, it re.escapereturns a character with a backslash in front of it. Otherwise, it returns the character itself.

+4
source

re.escape all :

>>> def checker(st):
...   return all(re.escape(i)==i for i in st)
... 
>>> checker('aab]')
False
>>> checker('aab')
True
>>> checker('aa.b3')
False
0

Per , re.escape ( ):

-- backslashed; , .

, , , . :

>>> re.escape('&') == '&'
False

, , , , , . , , - , :

char in set(r'.^$*+?{}[]\| ')
-1

, (IMHO) () / "" , Regex Python -

def isFalsePositive(char):
    m = re.match(char, 'a')
    if m is not None and m.end() == 1:
        return True
    else:
        return False

def isSpecial(char):
    try:
        m = re.match(char, char)
    except:
        return True

    if m is not None and m.end() == 1:
        if isFalsePositive(char):
            return True
        else:
            return False
    else:
        return True

PS - The isFalsePositive () page may be redundant to check for a special case. (Dot).:-)

-1
source

All Articles