gpt4 book ai didi

python - 正则表达式多行替换

转载 作者:行者123 更新时间:2023-12-01 05:44:33 24 4
gpt4 key购买 nike

所以我有这个:

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

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

最佳答案

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

从 python 文档复制 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>'.

关于python - 正则表达式多行替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16516093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com