[英]Regex multiline replace
So I have this: 所以我有这个:
z='===hello
there===,
how are ===you===?'
And I want to be: 我想成为:
z='<b>hello
there<\b>,
how are <b>you<\b>?'
I tried doing this: 我尝试这样做:
z = re.sub(r"\={3}([^\$]+)\={3}", r"<b> \\1 </b>", z, re.M)
And it works sort of but I got this instead: 它的工作原理是这样的,但我得到了这个:
z='<b>hello
there===,
how are ===you<\b>?'
I'm still new to this but I believe it's the ^
and $
that makes it match the beginning and the end of the string. 我对此还不陌生,但我相信是^
和$
使其与字符串的开头和结尾匹配。 So how do I change it so it matches the ones in the middle? 那么,如何更改它,使其与中间的匹配?
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>'.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.