简体   繁体   English

如何在不使用反斜杠的情况下转义Python Regex特殊字符

[英]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. 我的问题是lbtests词典有时会解析为包含括号的字符串,例如Basophils (Abs) ,因此程序认为我正在尝试创建一个组。 Instead, I want it to match the string "Basophils (Abs)". 相反,我希望它匹配字符串“ 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. 使用re.escape(lbtests['lbname'])可以对字符串进行转义以使其完全匹配。

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 re.escapere.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 https://docs.python.org/3/library/re.html#re.escape

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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