2010-01-19 44 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