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

Python正则匹配mmm dd格式日期仅返回月份,如何修正?

问题分析与解决

问题原因

你写的正则表达式里,({}) 把月份列表包裹成了捕获组,而re.findall()的特性是:当正则包含捕获组时,会优先返回捕获组匹配的内容,而非整个匹配的完整字符串。所以最终结果只拿到了月份,没包含后面的日期部分。

解决方法

有两种简洁的修复方式:

方式1:使用非捕获组(推荐)

把正则里的捕获组({})改成非捕获组(?:{}),非捕获组不会被findall单独提取,这样就会返回完整的"mmm dd"匹配结果。

修改后的代码:

import re

strings = ["Get it by may 1 - june 15", "Arrives between may 1 and june 15"]    
months = ['january', 'jan', 'february', 'feb', 'march', 'mar', 'april', 'apr', 'may', 'june', 'jun', 'july', 'jul', 'august', 'aug', 'september', 'sept', 'sep', 'october', 'oct', 'november', 'nov', 'december', 'dec']

# 将捕获组改为非捕获组 (?:...)
pattern = r'\b(?:{})\s\d{{1,2}}'.format('|'.join(months))

for string in strings:
      matches = re.findall(pattern, string)
      print(f"String: {string}")
      print(f"Matches: {matches}")

运行输出:

String: Get it by may 1 - june 15
Matches: ['may 1', 'june 15']
String: Arrives between may 1 and june 15
Matches: ['may 1', 'june 15']

方式2:给整个正则加外层捕获组

如果后续需要单独提取月份和日期,可以给整个匹配模式加外层捕获组,再从结果中取出完整匹配内容:

import re

strings = ["Get it by may 1 - june 15", "Arrives between may 1 and june 15"]    
months = ['january', 'jan', 'february', 'feb', 'march', 'mar', 'april', 'apr', 'may', 'june', 'jun', 'july', 'jul', 'august', 'aug', 'september', 'sept', 'sep', 'october', 'oct', 'november', 'nov', 'december', 'dec']

# 外层添加捕获组,确保能拿到完整匹配结果
pattern = r'\b(({})\s\d{{1,2}})'.format('|'.join(months))

for string in strings:
      matches = re.findall(pattern, string)
      # 提取每个元组的第一个元素,即完整的日期字符串
      full_matches = [match[0] for match in matches]
      print(f"String: {string}")
      print(f"Matches: {full_matches}")

这种方式适合需要同时获取完整日期和单独月份的场景,若只需要完整日期,方式1更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:45:21