Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式,如何替换图表中两个单词之间的文本?_Python_Regex - Fatal编程技术网

Python正则表达式,如何替换图表中两个单词之间的文本?

Python正则表达式,如何替换图表中两个单词之间的文本?,python,regex,Python,Regex,假设我有一个多行字符串,如下所示: """ Some initial text.... Heading1 Some other text..... Heading2 Some more text.... """ 因此,为了找到标题1和标题2之间的文本,我尝试以下方法: search1 = re.search('(Heading1)(.*)(Heading2)', string, flags=re.DOTALL) print "Search result: \n" + str(search1.g

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

"""
Some initial text....
Heading1
Some other text.....
Heading2
Some more text....
"""
因此,为了找到标题1和标题2之间的文本,我尝试以下方法:

search1 = re.search('(Heading1)(.*)(Heading2)', string, flags=re.DOTALL)
print "Search result: \n" + str(search1.group(0))
这为我提供了标题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....
"""

非常感谢。

您也可以在正则表达式中使用DOTALL修饰符

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

看起来像。是Python 2.7吗?(注意,如果您有多个段落,我会选择延迟匹配:
(Heading1)(.*)(Heading2)
)。好吧,它。或者
r'(Heading1)([\s\s]*?)(Heading2)
@AvinashRaj伟大的答案!你能推荐一些好的正则表达式教程吗?我从SO那里学到了所有正则表达式的东西。本网站涵盖所有regex口味。@AvinashRaj来自钦奈的顶级用户,编号为2Gethu ponga kalakuringha