简体   繁体   中英

How to escape Python Regex special characters without using backslash

I have a regular expression that looks something like this:

pattern = "".join([
     '^', 
     lbtests['lbname'], 
     '\d{4}',
     '[A-Za-z]{2},
     '$'
])

re.compile(pattern)

My problem is that the lbtests dictionary sometimes resolves to a string that contains parentheses, eg Basophils (Abs) , so the program thinks I'm trying to create a group. Instead, I want it to match the string "Basophils (Abs)".

Is there a way to escape the parentheses without using backslashes? If not, is there a better way to go about this?

Use re.escape(lbtests['lbname']) to escape the string to match it exactly.

Example:

>>> import re
>>> lbtests = {'lbname':'Basophils (Abs)'}
>>> re.escape(lbtests['lbname'])
'Basophils\\ \\(Abs\\)'

Note that it escapes the space as well as the parentheses, so it will match exactly.

Check out re.escape

import re

if __name__ == '__main__':
    pattern = f'hello {re.escape("(world)")}'
    print(re.match(pattern, 'hello (world)'))

    # output: 
    # <re.Match object; span=(0, 13), match='hello (world)'>

https://docs.python.org/3/library/re.html#re.escape

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM