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

如何使用regex在Python中提取指定格式的英文日期文本

Python正则提取指定格式日期实现方案

根据你给出的4类日期格式共性,正则会匹配以下特征的字符串:

  • 开头为1~2位表示日期的阿拉伯数字
  • 可选择性匹配带空格的序数后缀(th/st/nd/rd)
  • 可选择性匹配日期和day之间的英文句号与空格
  • 固定匹配标识段「day of」
  • 匹配首字母大写的英文月份
  • 可选择性匹配年份前的逗号
  • 结尾为4位数字年份

匹配正则表达式为:r'\b\d{1,2}(?:\s*(?:th|st|nd|rd))?\s*\.?\s*day of [A-Z][a-z]+,?\s*\d{4}\b'

完整Python实现代码如下:

import re

# 预编译正则规则
date_pattern = re.compile(r'\b\d{1,2}(?:\s*(?:th|st|nd|rd))?\s*\.?\s*day of [A-Z][a-z]+,?\s*\d{4}\b')

# 测试用例
test_sentences = [
    "Ujjwal was born on 12th day of August 1998",
    "Rahul started the business on 30th day of June, 2003",
    "RK was married on 18 th .day of March 2008",
    "Raj had a baby on 11 day of June, 2012"
]

# 提取并输出结果
for idx, sent in enumerate(test_sentences, 1):
    match_res = date_pattern.search(sent)
    if match_res:
        print(f"用例{idx}提取结果:{match_res.group()}")

运行输出结果:

用例1提取结果:12th day of August 1998
用例2提取结果:30th day of June, 2003
用例3提取结果:18 th .day of March 2008
用例4提取结果:11 day of June, 2012

注:第一个用例目标日期写的2010属于输入笔误,原句中实际日期为1998,正则按原句内容提取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:51:00