首页 > 解决方案 > 使用正则表达式检索字符串的最后 3 个单词

问题描述

我正在尝试使用正则表达式检索字符串的最后 3 个单词。

字符串 - “来自 2019 年 7 月 19 日的地方”

我只需要提取日期部分“2019 年 7 月 19 日”。

我尝试了以下方法:-

(\w{3})$             # gives last 3 letters of the last word
([,0-9]{3})$         # gives last 3 digits from the last word
(?:\w+\s*){1,3}$     # retrieves only the last word

他们都没有给我最后三个字。

标签: regex

解决方案


尝试这个:

string = "From the place on July 19, 2019"
mobj = re.search(r"\b(\w+(?=\s\d+,)\s\d+,\s?\d+)", string)
date = mobj.group(1)

输出:

>>> print(date)
July 19, 2019

推荐阅读