So, I am successfully matching and extracting some special tagged text using the following regular expression:
theString = u"Var 1 value: %%v:123453%%, Var 2 value: %%v:984561%%, Var 3 value: %%v:123456%%"
p = re.compile("\%%v:([0-9]*)%%")
theIds = p.findall(theString)
That returns
[u'123453', u'984561', u'123456']
which is exactly what I need. Next, I need to replace those with some looked up value, so what I’d like to get next is this:
[u'Var 1 value: ', u', Var 2 value: ', u', Var 3 value: ']
So that I can glue those strings together with the looked up values from the first list, resulting in a string that looks something like this:
u”Var 1 value: Some Value, Var 2 value: 837, Var 3 value: more stuff”
Or, if there’s a better way to do the replacement I’m all ears.
Thanks in advance!
Use a replacement function to insert arbitrary substitutions. See the
re.subdocumentation for how the function works. Here is an example:The
insertLookupfunction will be called for each match, and is passed a MatchObject. We then use the matched value (u'123453', etc.) to look up the replacement value, which then is inserted intonewStringinstead of the matched string.