在Python中的正则表达式中转义特殊字符

use*_*851 2 python regex

我有一个字典和字符串,如:

d = {'ASAP':'as soon as possible', 'AFAIK': 'as far as I know'}
s = 'I will do this ASAP, AFAIK.  Regards, X'
Run Code Online (Sandbox Code Playgroud)

我想用字符串中的dict键替换dict的值并返回

I will do this <as soon as possible>, <as far as I know>.  Regards, X.
Run Code Online (Sandbox Code Playgroud)

我用

pattern = re.compile(r'\b(' + '|'.join(d.keys())+r')\b')
result=pattern.sub(lambda x: '<'+d[x.group()]+'>',s)
print"result:%s" % result
Run Code Online (Sandbox Code Playgroud)

我有一个字典,如:

{'will you wash some pants for me please :-)': 'text'}
Run Code Online (Sandbox Code Playgroud)

笑脸导致错误.如何更改我的正则表达式以适应像表情符号这样的任何字符?

Mar*_*ers 7

您需要转义任何正则表达式元字符re.escape():

pattern = re.compile(r'\b(' + '|'.join(map(re.escape, d)) + r')\b')
Run Code Online (Sandbox Code Playgroud)