4

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?

Iguananaut
  • 19,186
  • 4
  • 48
  • 59
user1189851
  • 4,581
  • 14
  • 46
  • 67

1 Answers1

10

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

pattern = re.compile(r'\b(' + '|'.join(map(re.escape, d)) + r')\b')
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187