首页 > 解决方案 > 在 Python 中使用开始/结束标记搜索/替换标头

问题描述

我是 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

标签: pythonregexstring

解决方案


它来了:

\*_____________________________([\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)

推荐阅读