Python的re.sub问题

问候一切,

我不知道这是否可能,但我想在正则expression式replace中使用匹配的组来调用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 

想法?

你可以指定一个callback,当使用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) 

还注意到额外的? 在正则expression式中。 你想在这里非贪婪的匹配。

我明白,这只是示例代码来说明一个概念,但对于你给的例子,简单的string格式更好。

听起来像矫枉过正 为什么不只是做一些像

 text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar') 

 >>> 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:]]'