Python re.sub问题

net*_*ate 15 python regex

问候所有,

我不确定这是否可行,但我想在正则表达式替换中使用匹配的组来调用变量.

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
Run Code Online (Sandbox Code Playgroud)

想法?

Chr*_*ard 28

您可以在使用可以访问组的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)
Run Code Online (Sandbox Code Playgroud)

还要注意额外的?在正则表达式中.你想在这里进行非贪婪的匹配.

我理解这只是用于说明概念的示例代码,但是对于您给出的示例,简单的字符串格式化更好.

  • 我回答了你的问题,但我认为你问的是错误的问题.适当时,请优先使用字符串格式优先于正则表达式.Noufal Ibrahim回答了你应该问的问题. (2认同)

Nou*_*him 8

听起来有点矫枉过正.为什么不做一些像

text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')
Run Code Online (Sandbox Code Playgroud)