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)).*
Answer
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.
No comments:
Post a Comment