Tuesday, February 20, 2018

python - 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)).*

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...