Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the last 3 words of a string using regex [duplicate]

Tags:

regex

I'm trying to retrieve the last 3 words of a string using regex.

The string - "From the place on July 19, 2019"

I need to extract only the date part 'July 19,2019'.

I tried the below ways :-

(\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

None of them gives me the last 3 words.

like image 584
Salih Avatar asked Oct 14 '25 08:10

Salih


1 Answers

Try this:

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)

Output:

>>> print(date)
July 19, 2019
like image 76
Shubham Sharma Avatar answered Oct 19 '25 23:10

Shubham Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!