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

如何使用正则表达式提取指定关键词附近的对应日期

正则提取指定关键词后对应日期的实现方案

核心正则表达式

你可以用正向肯定后向断言规则匹配需求,对应正则如下:
(?<=Date of admission: )\d{2}\/\d{2}\/\d{4}

规则说明

  • (?<=Date of admission: ) 属于正向后向断言,仅匹配前方恰好是「指定关键词+空格」的内容,这部分不会被计入提取结果
  • \d{2}\/\d{2}\/\d{4} 用于匹配DD/MM/YYYY格式的日期,即2位数字+斜杠+2位数字+斜杠+4位数字

代码实现示例(Python)

import re

# 给定待匹配文本
input_text = "I went to hospital and admitted. Date of admission: 12/08/2019 and surgery of Date of surgery: 15/09/2015. Date of admission: 12/05/2018 is admitted Raju"
# 指定匹配关键词
target_keyword = "Date of admission:"

# 构造正则匹配规则,re.escape用于规避关键词中特殊字符的影响
match_pattern = re.compile(rf'(?<={re.escape(target_keyword)} )\d{{2}}\/\d{{2}}\/\d{{4}}')
# 提取所有匹配结果
extract_result = match_pattern.findall(input_text)

print(extract_result)
# 输出结果:['12/08/2019', '12/05/2018']

扩展适配

如果关键词和日期之间可能存在多个空格、制表符等空白字符,可以将正则调整为(?<=Date of admission:)\s*\d{2}\/\d{2}\/\d{4},其中\s*可以匹配0到多个任意空白字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:18:01