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

如何使用正则提取缺失月份或日期的不完整日期并完成格式转换

问题原因

原有代码直接对匹配结果调用group()方法,当对应格式的日期不存在时,re.search()会返回None,此时调用group()就会抛出AttributeError报错,之前的try except未生效大概率是异常捕获范围不对,或者没有对每个匹配结果单独做存在性判断。

方案1:保留原有逻辑+正确异常处理

import re

date_n = '2022-12'
# 先初始化字段默认值为None,可按需求修改为空字符串等默认值
year = month = day = None

try:
    match_year = re.search(r'(?P<year_only>(?P<year>\d+))', date_n)
    if match_year:
        year = match_year.group('year_only')
    
    match_month = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+))', date_n)
    if match_month:
        month = match_month.group('month')
    
    match_day = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+))', date_n)
    if match_day:
        day = match_day.group('day')
except:
    # 可按需添加错误日志打印逻辑
    pass

print(year, month, day) # 输出结果:2022 12 None

方案2:更高效的单正则兼容写法

只用一次正则匹配就可以覆盖三种不完整日期场景,不需要多次匹配,也不需要额外异常捕获:

import re

# 兼容仅年份、年月、完整日期三种格式的正则
date_pattern = re.compile(r'(?P<year>\d{4})(?:-(?P<month>\d{1,2})(?:-(?P<day>\d{1,2}))?)?')

date_n = '2022-12'
match_res = date_pattern.search(date_n)
if match_res:
    year = match_res.group('year')
    month = match_res.group('month')
    day = match_res.group('day')

print(year, month, day) # 输出结果:2022 12 None

正则说明:

  • 强制匹配4位年份存入year分组
  • 月份部分用可选非捕获组包裹,存在则存入month分组,不存在则为None
  • 日期部分嵌套在月份可选组内,仅存在月份时才会匹配,不存在则为None
    完全覆盖三种场景:仅年份2023、年月2023-10、完整日期2023-10-07。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:01