正则表达式提取日期求助:从指定字符串匹配对应月份日期
解决方案
你的需求是将日期与对应的月份关联,同时提取末尾年份,单一正则很难直接完成这种分组关联,推荐用分步处理的方式,逻辑更清晰且易维护:
步骤说明
- 先提取末尾的两位年份;
- 剥离字符串开头的
C+和末尾的年份部分,聚焦中间的日期-月份内容; - 分割内容单元,逐个判断是否包含月份标记(
.\d.),将日期按所属月份分组。
代码实现
import re from collections import defaultdict # 原始字符串 raw_str = 'C+11.,18.,25.6.,2.,23.7.,27.8.23' # 1. 提取末尾年份 year = re.search(r'\d{2}$', raw_str).group() # 2. 清理字符串:移除开头的C+和末尾的年份部分 cleaned_str = re.sub(r'^C\+|\.\d{2}$', '', raw_str) # 3. 分割为单个单元,按月份分组日期 date_units = cleaned_str.split(',') month_date_map = defaultdict(list) current_dates = [] for unit in date_units: # 检查当前单元是否包含月份标记(.\d.) month_match = re.search(r'\.(\d)\.', unit) if month_match: # 提取当前单元中的日期 date = re.match(r'(\d{1,2})\.', unit).group(1) current_dates.append(date) # 将当前日期组关联到对应月份 month = month_match.group(1) month_date_map[month] = current_dates.copy() # 重置当前日期组,为下一个月份准备 current_dates = [] else: # 单纯的日期单元,加入当前日期组 date = re.match(r'(\d{1,2})\.', unit).group(1) current_dates.append(date) # 加入年份信息 month_date_map['year'] = year # 输出结果 print(dict(month_date_map))
输出结果
{'6': ['11', '18', '25'], '7': ['2', '23'], '8': ['27'], 'year': '23'}
原正则问题说明
你的原正则只匹配了每个月份前的最后一个日期,因为正向预查的逻辑限制了只能捕获紧邻月份的日期。而日期与月份的关联是多对一的分组关系,正则擅长匹配模式,但不擅长处理这种上下文分组,分步处理更符合逻辑直觉。
内容的提问来源于stack exchange,提问作者Ferroum Samir
相关产品推荐
相关产品推荐

