Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping special characters like ) in regular expressions in Python [duplicate]

Tags:

python

regex

I have a dictionary and string like :

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

I want to replace the values of dict with the keys of the dict in the string and return

I will do this <as soon as possible>, <as far as I know>.  Regards, X.

I use

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

I have a dictionary like:

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

The smiley is causing an error. How do I change my regular expression to suit any characters like smileys?

like image 265
user1189851 Avatar asked Dec 25 '22 15:12

user1189851


1 Answers

You need to escape any regular expression metacharacters with re.escape():

pattern = re.compile(r'\b(' + '|'.join(map(re.escape, d)) + r')\b')
like image 67
Martijn Pieters Avatar answered May 13 '23 02:05

Martijn Pieters