在Python正则表达式中如何转义特殊字符,比如 )?

4

我有一个字典和字符串:

d = {'ASAP':'as soon as possible', 'AFAIK': 'as far as I know'}
s = 'I will do this ASAP, AFAIK.  Regards, X'

我希望将字典的键替换为字符串中对应的值并返回。
I will do this <as soon as possible>, <as far as I know>.  Regards, X.

我使用

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

我有一个类似于字典的数据结构:

{'will you wash some pants for me please :-)': 'text'}

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

1
你尝试在键上使用re.escape了吗? - Corley Brigman
1
你真正想问的是如何在正则表达式中转义特殊字符...与此无关的是字典。 - Iguananaut
1个回答

10

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

pattern = re.compile(r'\b(' + '|'.join(map(re.escape, d)) + r')\b')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接