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

Python 3.9正则表达式匹配特定格式字符串并排除含TP的项

解决方案

场景1:保留所有符合原格式且不含TP的项(含TK的自动被保留)

直接在原正则的中间部分添加负向预查,排除TP组合:

import re

pattern = r'[BPC][3-9]\d{2}-(?!TP)[A-Z]{2}-[1-2]\d{3}'
with open('your_file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

matches = re.findall(pattern, content)
print(matches)

正则说明:

  • (?!TP) 是负向预查,确保当前位置后不是TP,直接排除所有中间两位为TP的匹配项
  • 原格式的其他规则保持不变,含TK的项会被正常匹配

场景2:仅保留中间两位为TK的项(自动排除TP)

如果需求是只提取中间两位明确为TK的项,直接把原正则的[A-Z]{2}替换为TK即可:

import re

pattern = r'[BPC][3-9]\d{2}-TK-[1-2]\d{3}'
with open('your_file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

matches = re.findall(pattern, content)
print(matches)

补充说明

如果文本中存在跨行的匹配项(比如目标字符串被换行拆分),可以在re.findall()中添加re.DOTALL参数,让正则匹配换行符:

matches = re.findall(pattern, content, re.DOTALL)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:40:46