You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python3正则表达式替换多行指定区间内容?

解决方案

直接用Python的re.sub()结合非贪婪匹配就能搞定,步骤如下:

  1. 定义好要替换的新内容,读取原文件全部内容
  2. 用正则匹配#---START---到#---END---之间的所有内容(含换行),用非贪婪模式避免误匹配多个区间
  3. 将匹配段替换为#---START---+新内容+#---END---
  4. 把替换后的内容写回原文件

完整代码示例:

import re

# 新内容,保留原换行格式
new_content = """Rain

The rain is raining all around,
It falls on field and tree,
It rains on the umbrellas here,
And on the ships at sea."""

# 读取原文件
with open('poem.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 执行正则替换
updated_content = re.sub(
    r'#---START---\n.*?\n#---END---',
    f'#---START---\n{new_content}\n#---END---',
    content,
    flags=re.DOTALL  # 让正则的.能匹配换行符
)

# 写回文件
with open('poem.txt', 'w', encoding='utf-8') as f:
    f.write(updated_content)

关键细节

  • 必须加re.DOTALL标记,否则.无法匹配换行符,跨多行的内容匹配不到
  • .*?是非贪婪匹配,确保只匹配从第一个#---START---到最近的#---END---区间,不会误抓多个区间
  • 读写文件指定encoding='utf-8',避免特殊字符乱码

内容的提问来源于stack exchange,提问作者chin wooi Ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:32:32