I have a string consisting of elements. Each element can contain "pear" or "apple". I can get all the elements using:
s = '<tag>uTSqUYRR8gapple</tag><tag>K9VGTZM3h8</tag><tag>pearTYysnMXMUc</tag><tag>udv5NZQdpzpearz5a4oS85mD</tag>'
import re; re.findall("<tag>.*?</tag>", s)
However, I want to get the last element that contains pear. What would the easiest/quickest way to do this? Is this a good way:
list = re.findall("<tag>.*?</tag>", s)
list.reverse()
last = next(x for x in list if re.match('.*pear', x))
re.match('<tag>(.*)</tag>', last).group(1)
or should I use a parser instead?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…