goul
goul

Reputation: 853

Last occurrence of a word and trailing

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

Answers (3)

shubhadeep
shubhadeep

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

Thierry Lathuille
Thierry Lathuille

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

Abid Hasan
Abid Hasan

Reputation: 658

Would this work?

potato(?!.*potato)(.*)

Upvotes: 2

Related Questions