Skip to main content
 首页 » 编程设计

python之如何在 python 中使用正则表达式在特定单词之前获取特定模式的所有日期或关键字

2024年11月01日41Leo_wl

我有以下字符串,我需要所有年份范围(例如 2018-19)出现在关键字 overall production 之前。

详情单位/基数 2017-18 2018-19 6月(P) 4月-6月(P)\r\n(P) 2018-19 2019-20 2018-19 2019-20\r\n 总体产量 2014-15 2015-16 月产量

我试过:

re.findall(r"(\d{4}-\d{2})", string) 

这让我回归: ['2017-18', '2018-19', '2018-19', '2019-20', '2018-19', '2019-20', '2014-15', '2015-16 ']。在这里我不想要过去两年 '2014-15', '2015-16' 因为它在关键字 overall production

之后

我也尝试过:

re.findall(r"(\d{4}-\d{2}).+overall production", string) 

但我只得到第一年的范围 ['2017-18']

有人可以帮我写一个正确的正则表达式,这样我就可以在我传递的特定关键字之前获得所有年份范围(无论计数如何)。

请您参考如下方法:

第二次尝试中的 .+overall production 消耗了所有文本,包括 overall production,这就是为什么只返回第一个范围(有此匹配后没有第二个 overall production 子串)。

您可以使用基于前瞻的解决方案:

re.findall(r'\b\d{4}-\d{2}\b(?=.*overall production)', text, re.DOTALL) 

参见 regex demo

详情

  • \b - 单词边界
  • \d{4}-\d{2} - 四位数,-,两位
  • \b - 单词边界
  • (?=.*overall production) - 需要(但不消耗)的正向前瞻,即它不会使正则表达式索引随匹配项移动并且不将匹配的文本添加到整体匹配值)任何 0+ 个字符,尽可能多,紧跟在当前位置右侧的 overall production 子字符串。