2010-01-19 51 views
14

大家好,Python的应用re.sub问题

我不知道这是可能的,但我想使用匹配的组正则表达式替换调用变量。

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 

想法?

+0

ha!不是真的。熟悉py,perl和php - 没有任何主人。感谢您的帮助:) – netricate

回答

24

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

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

我明白这只是示例代码来说明一个概念,但对于您给出的示例,简单的字符串格式更好。

+0

感谢您的代码!这实际上更接近我的想法。 – netricate

+2

我回答了你的问题,但我认为你问的是错误的问题。适当时,请使用字符串格式优先于正则表达式。努瓦尔易卜拉欣回答了你应该问的问题。 –

+0

不要忘记返回语句中的引号。 :) –

8

听起来像矫枉过正。为什么不做点像

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

+0

文本存储在数据库中。我想我可以用%()值替换所有的[[::]]值,这应该工作。我会试一试。谢谢! – netricate

+0

该方法取决于您是否知道[[:a:]]和[[:b:]]的位置。 – ghostdog74

+0

有很多问题,但OP想要做什么在概念上与字符串格式相同。 –

2
>>> 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:]]' 
+0

感谢再看看这个。很酷! :) – netricate