【问题标题】:Escaping special characters like ) in regular expressions in Python [duplicate]在 Python 的正则表达式中转义特殊字符,如 ) [重复]
【发布时间】:2014-02-04 05:09:06
【问题描述】:

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

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

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

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'}

笑脸导致错误。如何更改我的正则表达式以适应笑脸等任何字符?

【问题讨论】:

  • 你试过在按键上使用re.escape吗?
  • 你真正要问的是如何在正则表达式中转义特殊字符......字典与它无关。

标签: python regex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 2013-12-28
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    相关资源
    最近更新 更多