Greetings all,
I’m not sure if this is possible but I’d like to use matched groups in a regex substitution to call variables.
a = 'foo'
b = 'bar'
text = 'find a replacement for me [[:a:]] and [[:b:]]'
desired_output = 'find a replacement for me foo and bar'
re.sub('[[:(.+):]]',group(1),text) #is not valid
re.sub('[[:(.+):]]','1',text) #replaces the value with 'a' or 'b', not var value
thoughts?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can specify a callback when using re.sub, which has access to the groups:
http://docs.python.org/library/re.html#text-munging
a = 'foo'
b = 'bar'
text = 'find a replacement for me [[:a:]] and [[:b:]]'
desired_output = 'find a replacement for me foo and bar'
def repl(m):
contents = m.group(1)
if contents == 'a':
return a
if contents == 'b':
return b
print re.sub('[[:(.+?):]]', repl, text)
Also notice the extra ? in the regular expression. You want non-greedy matching here.
I understand this is just sample code to illustrate a concept, but for the example you gave, simple string formatting is better.
Method 2
Sounds like overkill. Why not just do something like
text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')
?
Method 3
>>> d={}
>>> d['a'] = 'foo'
>>> d['b'] = 'bar'
>>> text = 'find a replacement for me [[:a:]] and [[:b:]]'
>>> t=text.split(":]]")
>>> for n,item in enumerate(t):
... if "[[:" in item:
... t[n]=item[: item.rindex("[[:") +3 ] + d[ item.split("[[:")[-1]]
...
>>> print ':]]'.join( t )
'find a replacement for me [[:foo:]] and [[:bar:]]'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0