Python re.sub 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2094975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:45:55  来源:igfitidea点击:

Python re.sub question

pythonregex

提问by netricate

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'

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('\[\[:(.+):\]\]','',text) #replaces the value with 'a' or 'b', not var value

thoughts?

想法?

回答by Christian Oudard

You can specify a callback when using re.sub, which has access to the groups: http://docs.python.org/library/re.html#text-munging

您可以在使用 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)

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.

我知道这只是用于说明概念的示例代码,但对于您提供的示例,简单的字符串格式会更好。

回答by Noufal Ibrahim

Sounds like overkill. Why not just do something like

听起来有点矫枉过正。为什么不做类似的事情

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

?

?

回答by ghostdog74

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