1

所以我有这个:

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>?'  

我对此仍然很陌生,但我相信它是^and$使它匹配字符串的开头和结尾。那么如何更改它以使其与中间的匹配?

4

1 回答 1

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

从python doc复制点击这里

*?, +?, ?? 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>'.

于 2013-05-13T06:38:11.927 回答