2013-08-27 128 views
2

我搜索了現有的問題,但他們似乎沒有回答這個具體問題。Python正則表達式多行替換

我有以下的Python程序

description = """\ 
before 

{cs:id=841398|rep=myrepo}: after 
""" 
pattern = re.compile(r"(.*)\{cs:id=(.*)\|rep=(.*)\}(.*)") 

,我需要更換正則表達式的描述看起來像下面,但我不能讓模式和替代語法正確

description="""\ 
before 

<a href="http://crucible.app.com:9090/myrepo?cs=841398">841398</a> : after 
""" 

坩堝.app.com:9090是我預先提供的一個常量,所以我基本上需要用我的替換替換模式。

有人可以告訴我什麼是最好的Python正則表達式查找和替換這個語法?

+0

你看着['re.sub'(http://docs.python.org/2/library/re.html)? – Jerry

回答

2

您的模式中不需要第一個和最後一個(.*)。寫回拍攝組在替換字符串,用\1\2

description = re.sub(pattern, "<a href=\"http://crucible.app.com:9090/\2?cs=\1\">\1</a>", description) 

順便說一句,另一種方式來提高你的圖形(性能 - 和魯棒性-wise)被以mkae內重複更加明確,使他們不小心走過去的|}

pattern = re.compile(r"\{cs:id=([^|]*)\|rep=([^}]*)\}") 

您還可以使用命名組:

pattern = re.compile(r"\{cs:id=(?P<id>[^|]*)\|rep=(?P<rep>[^}]*)\}") 

然後在替換字符串:

"<a href=\"http://crucible.app.com:9090/\g<repo>?cs=\g<id>\">\g<id></a>" 
2

使用re.sub/RegexObject.sub

>>> pattern = re.compile(r"{cs:id=(.*?)\|rep=(.*?)}") 
>>> description = pattern.sub(r'<a href="http://crucible.app.com:9090/\1?cs=\2">\1</a>', description) 
>>> print(description) 
before 

<a href="http://crucible.app.com:9090/841398?cs=myrepo">841398</a>: after 

\1\2指匹配組1,2。

我稍微修改了正則表達式。

  • 無需轉義{,}
  • 在{..}之前,之後刪除捕獲組。
  • 使用非貪婪匹配:.*?