正则表达式多行替换

时间:2013-05-13 06:34:29

标签: python regex

所以我有这个:

z='===hello  
there===,  
how are ===you===?'

我想成为:

z='<b>hello  
there<\b>,  
how are <b>you<\b>?'

我试过这样做:

z = re.sub(r"\={3}([^\$]+)\={3}", r"<b> \\1 </b>", z, re.M)  

它的工作方式有点但我得到了这个:

z='<b>hello  
there===,  
how are ===you<\b>?'  

我还是新手,但我相信它是^$,使它匹配字符串的开头和结尾。那么我如何更改它以匹配中间的?

1 个答案:

答案 0 :(得分:2)

re.sub(r"\={3}([^\$]+?)\={3}", r"<b> \\1 </b>", z, re.M)

从python doc Click Here复制:

  

*?, +?, ?? The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.