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

如何用正则表达式移除文本中动态变化的特定格式日期字符串?

移除“日 月份缩写 年”格式日期的解决方案

你的原正则表达式匹配的是带点的数字组合,和目标日期格式(如14 Sept 2021)完全不匹配,所以无法生效。以下是正确的实现方案:

正确的正则表达式

匹配目标格式的正则为:

\b\d{1,2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec) \d{4}\b

各部分含义:

  • \b:单词边界,避免日期和其他字符粘连(比如abc14 Sept 2021def不会被误匹配)
  • \d{1,2}:匹配1-2位的日期(支持1号到31号)
  • (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec):覆盖所有英文月份的缩写,包含Sep和Sept两种写法
  • \d{4}:匹配4位年份
  • 空格:分隔日、月、年的固定空格

修改后的代码

import re

def clean_up_answer(answer):
    date_pattern = r'\b\d{1,2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec) \d{4}\b'
    # 替换所有匹配到的日期为空字符串,无匹配时直接返回原内容
    cleaned_answer = re.sub(date_pattern, '', answer)
    return cleaned_answer.strip()

额外优化

如果月份缩写存在大小写混合(如SEPT、sept),可以添加忽略大小写的标志:

cleaned_answer = re.sub(date_pattern, '', answer, flags=re.IGNORECASE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:30:53