Python re.sub 问题 [英] Python re.sub question

查看:57
本文介绍了Python re.sub 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

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

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

想法?

推荐答案

您可以在使用 re.sub 时指定回调,它可以访问组:http://docs.python.org/library/re.html#text-munging

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.

这篇关于Python re.sub 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆