Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.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_String - Fatal编程技术网

用Python中的开始/结束标记搜索/替换标题

用Python中的开始/结束标记搜索/替换标题,python,regex,string,Python,Regex,String,我是Python新手,我有一项任务,我需要以一种特定的方式清理文件中的头,因为现在没有关于我的头的标准,我正在尝试提出这个脚本,以便在多个实例中重用 示例文件: *_____________________________ * This is header text * For details, see foobar.txt. *_____________________________ * * * Code goes here Code = x 我必须这样做的方式是定义标题的开始和结束位置

我是Python新手,我有一项任务,我需要以一种特定的方式清理文件中的头,因为现在没有关于我的头的标准,我正在尝试提出这个脚本,以便在多个实例中重用

示例文件:

*_____________________________
* This is header text
* For details, see foobar.txt.
*_____________________________
*
*

* Code goes here
Code = x
我必须这样做的方式是定义标题的开始和结束位置,然后在添加新标题之前清除中间的所有内容(包括开始/结束点)

目前我正在尝试使用我的

start_pos = r"*_____________________________"
end_pos = r"""*_____________________________
    *
    *"""

然后搜索中间的所有东西。然后,我希望将所有文件合并,然后删除/替换,使我的新文件如下所示:

*
* Hello, world.
*

* Code goes here
Code = x
来了:

\*_____________________________([\s\S]*?)\*_____________________________(?:\n\*){2}

为了匹配中间的内容,我们可以使用一个修改过的“点”
[\s\s]
,它匹配包括换行符在内的所有内容。“点”匹配延迟,以避免匹配过多

:


@是的!我很难弄清楚如何在中间分离出这个群体。只要稍加调整,我就可以让它与其他用例一起工作。谢谢。当然,你可以把它作为完整的答案贴出来。
import re
regex = r"\*_____________________________([\s\S]*?)\*_____________________________(?:\n\*){2}"
test_str = ("*_____________________________\n"
    "* This is header text\n"
    "* For details, see foobar.txt.\n"
    "*_____________________________\n"
    "*\n"
    "*\n\n"
    "* Code goes here\n"
    "Code = x\n")
subst = "*\\n* Hello, world.\\n*"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)