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
  • 21,810
  • 5
  • 50
  • 63
user1189851
  • 4,861
  • 15
  • 47
  • 69

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
  • 1,048,767
  • 296
  • 4,058
  • 3,343