问候所有,
我不确定这是否可行,但我想在正则表达式替换中使用匹配的组来调用变量.
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)
还要注意额外的?在正则表达式中.你想在这里进行非贪婪的匹配.
我理解这只是用于说明概念的示例代码,但是对于您给出的示例,简单的字符串格式化更好.
听起来有点矫枉过正.为什么不做一些像
text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')
Run Code Online (Sandbox Code Playgroud)
?
| 归档时间: |
|
| 查看次数: |
13001 次 |
| 最近记录: |