Python re.sub question

后端 未结 3 1214
南旧
南旧 2020-11-28 12:58

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         


        
3条回答
  •  臣服心动
    2020-11-28 13:31

    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.

提交回复
热议问题