Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find last word in a string (Python)

Tags:

python

regex

I am trying to write a simple regex that finds if the last word in the string is a specific one.

I wrote something like this "(\W|^)dog$". (Check if last word in the sentence is dog)

This regex is correct but in python it is returning nothing when i type something like "I like dog".

I tested this in the Rubular regex editor and it seems to work.

Am I doing something wrong ?

EDIT : Adding my simple code

import re
pm = re.compile("(\W|^)dog$")
has = pm.match("i love dog")
print(has)
like image 876
rajaditya_m Avatar asked Oct 18 '13 16:10

rajaditya_m


1 Answers

You don't need to regex here. Simple split will do the job:

>>> s = "I like dog"
>>> s.rsplit(None, 1)[-1] == 'dog'
True

Since you need the last word only, str.rsplit can be used to start splitting from end, and passing 1 as 2nd argument, will only perform split only once. Then get the last element of the returned list.


As for doing this with regex, you would need to use re.search method, instead of re.match method. The later one matches at the beginning of the string, so you would need to build the regex to match the entire string. You can rather do:

pm = re.compile(r"\bdog$")
has = pm.search("i love dog")

\b is word boundary. See Live Demo.

To do the same with re.match, your regex should be - r".*dog$".

pm = re.compile(r".*dog$")
has = pm.match("i love dog")
like image 184
Rohit Jain Avatar answered Oct 16 '22 13:10

Rohit Jain