Reputation: 853
I am looking to match the last occurrence of a word (excluded) in a sentence with the remaining words.
Example Looking for the word "potato, ", expecting to select what's in bold:
potato, orange, potato, plum, pear, etc.
Regex I put together is something like this however not working fully
(potato:(?!.*potato)).*
Upvotes: 2
Views: 111
Reputation: 13
You can try without using regex :
str1 = "potato, orange, potato, plum, pear, etc."
str_index = str1.rfind("potato", 0,len(str1))
print str1[str_index + len("potato")::]
Output ::
, plum, pear, etc.
Upvotes: 0
Reputation: 24233
You can look for 1 or more groups of "anything followed by potato", without capturing them, then capture the rest of the string:
import re
regex = re.compile(r'(?:.*potato)+(.*)')
m = regex.match('potato, orange, potato, plum, pear, etc.')
m.groups(1)[0]
# ', plum, pear, etc.'
And as a plus, you don't have to make potato appear twice in the regex.
Upvotes: 1