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

Python正则表达式贪婪匹配求助:替换AAA与BBB间文本失败

解决方案

核心思路

要删除AAA和BBB之间的全部内容(仅保留AAA和BBB本身),需通过反向预查+正向预查精准定位中间区域,同时开启re.DOTALL模式让正则支持多行文本匹配。

修正后的代码

import re

haystack='''Other needs and/or restrictions:
Telephone visit on 11/16 @ 3:50 PM 
AAA This form has been electronically signed. 
Check for Accuracy. XXX authorized by Dr Zhivago (M.D.) 
This form contains your private health information that 
you may choose to release to another party; 
please review for Accuracy. 
BBB
'''

# 匹配AAA之后、BBB之前的所有内容(不包含AAA和BBB)
pattern = r'(?<=AAA).*?(?=BBB)'
# 开启DOTALL模式,让.可以匹配换行符
haystack = re.sub(pattern, '', haystack, flags=re.DOTALL)
print(haystack)

关键说明

  • (?<=AAA):反向预查,确保匹配内容紧跟在AAA之后
  • .*?:非贪婪匹配任意字符,避免过度匹配超出目标区域
  • (?=BBB):正向预查,确保匹配内容在BBB之前
  • re.DOTALL:让正则中的.可以匹配换行符,适配多行文本场景

执行结果

运行后输出:

Other needs and/or restrictions:
Telephone visit on 11/16 @ 3:50 PM 
AAA BBB

内容的提问来源于stack exchange,提问作者Soundar Rajan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:12:09