您可以在使用re.sub时指定回调,该回调可以访问组: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)
还注意到额外的吗?在正则表达式中。您要在此处进行非贪心匹配。
我了解这只是说明概念的示例代码,但是对于您给出的示例,简单的字符串格式更好。