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

Python re.search正则groupdict匹配日期时排除1410类连续4位数字方法

多格式日期提取正则优化

需求背景

需要从'14th oct'、'14oct'、'14.10'、'14 10'、'14/10'等多种格式的字符串中提取日期和月份。

初始实现

最初使用的代码如下:

query = '14.oct'
print(re.search(r'(?P<date>\b\d{1,2})(?:\b|st|nd|rd|th)?(?:[\s\.\-/_\\,]*)(?P<month>\d{1,2}|[a-z]{3,9})', query, re.I).groupdict())

运行query='14.oct'时输出结果符合预期:

{'date': '14', 'month': 'oct'}

存在问题

该代码会错误将字符串'1410'识别为日期和月份,不希望匹配这类无分隔符的连续4位数字,期望这类场景返回匹配结果None,要求仅调整正则匹配规则,且保留groupdict()的使用方式。
补充说明:此前提到的(1410)中的括号仅用于和其他文本做区分,实际需要排除的是纯4位连续数字'1410'。

最终解决方案

通过在正则中添加(?!\d{3,}\b)实现了需求,最终实现代码如下:

import re
queries = ['14 10', '14.10', '1410', '14-10', '14/10', '14,10', '17800', '14th oct', '14thoct', '14th-oct', '14th/oct', '14-oct', '14.oct', '14oct']
max_indent = len(max(queries, key = len)) + 1

for query in queries:
    if resp := re.search(r'(?P<date>\b(?!\d{3,}\b)\d{1,2})(?:\b|st|[nr]d|th)?(?:[\s.-/_\\,-]*)(?P<month>\d{1,2}|[a-z]{3,9})', query, re.I):
        print(f"{query:{max_indent}}- {resp.groupdict()}")
    else:
        print(f"{query:{max_indent}}- 'Not a date'")

运行结果

14 10    - {'date': '14', 'month': '10'}
14.10    - {'date': '14', 'month': '10'}
1410     - 'Not a date'
14-10    - {'date': '14', 'month': '10'}
14/10    - {'date': '14', 'month': '10'}
14,10    - {'date': '14', 'month': '10'}
17800    - 'Not a date'
14th oct - {'date': '14', 'month': 'oct'}
14thoct  - {'date': '14', 'month': 'oct'}
14th-oct - {'date': '14', 'month': 'oct'}
14th/oct - {'date': '14', 'month': 'oct'}
14-oct   - {'date': '14', 'month': 'oct'}
14.oct   - {'date': '14', 'month': 'oct'}
14oct    - {'date': '14', 'month': 'oct'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:09:03