python - 正则表达式多行替换

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

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

最佳答案

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/

相关文章:

Python 三重字符串引号声明

python - 如何从 Python 中的流(不是磁盘支持的文件)中读取 Excel 文件?

python - 如何检查磁盘是否在使用 python 的驱动器中?

c# - 按组名称匹配正则表达式中的组的更好方法是什么

python - 可选字符串与正则表达式不匹配

python - 如何在 Django Orm 中获取每个组的最新 n 条记录

python - 如何在 Python 3.11+ 中创建枚举而不将参数传递给 __init__?

python - 拆分存储每个子字符串索引的字符串

regex - 用 sed 替换两个已知字符串之间的未知字符串

c++ - 我应该如何提取此 url 获取字符串