Python regex,如何替换子图中两个单词之间的文本?

2024-04-27 16:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个多行字符串,如下所示:

"""
Some initial text....
Heading1
Some other text.....
Heading2
Some more text....
"""

为了找到标题1和标题2之间的文本,我试着这样做:

^{pr2}$

它提供了标题1和标题2之间的所有文本,现在我尝试使用re.sub公司将标题1和标题2之间的文本替换为:

new_text = re.sub('(Heading1)(.*)(Heading2)', r"\1 replaced with python script \3", string, flags=re.DOTALL)

但我得到了一个错误:

TypeError: sub() got an unexpected keyword argument 'flags'

我如何得到它,这样我的最终输出是这个?公司名称:

"""
Some initial text....
Heading1
replaced with python script
Heading2
Some more text....
"""

非常感谢。在


Tags: 字符串text文本re标题morewithscript