Reputation: 8709
Using a variable inside regex is easy and one way of achieving this is as:
>>> z = '23'
>>> re.sub(r'p[kv]', r"%s" %z, 'pvkkpkvkk')
'23kk23vkk'
But what if the replacement values are stored in a dictionary as:
d = {'k':'23', 'v':'24'}
and I want to use the dictionary to substitute the replacement values. I want something like this:
re.sub(r'p([kv])', r"%s" %d[\1], 'pvkkpkvkk')
I know this won't work. Please help me out to find the correct regex. Expected output is same as above.
Upvotes: 1
Views: 66
Reputation: 122036
You can pass an arbitrary function, that takes a single match
object and returns a string to replace it, as the repl
for re.sub
; for example:
>>> import re
>>> d = {'k': '23', 'v': '24'}
>>> re.sub(
r'p([kv])',
lambda match: d[match.group()[1]],
'pvkkpkvkk',
)
'24kk23vkk'
Upvotes: 2