Tuesday, 20 February 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...