如何用Python3正则表达式替换多行指定区间内容?
解决方案
直接用Python的re.sub()结合非贪婪匹配就能搞定,步骤如下:
- 定义好要替换的新内容,读取原文件全部内容
- 用正则匹配
#---START---到#---END---之间的所有内容(含换行),用非贪婪模式避免误匹配多个区间 - 将匹配段替换为
#---START---+新内容+#---END--- - 把替换后的内容写回原文件
完整代码示例:
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
相关产品推荐
相关产品推荐

