Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

python - Simple regex for simple xml string

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a parser, ie BeautifulSoup instead:

import re
from bs4 import BeautifulSoup

s = '<tag>uTSqUYRR8gapple</tag><tag>K9VGTZM3h8</tag><tag>pearTYysnMXMUc</tag><tag>udv5NZQdpzpearz5a4oS85mD</tag>'
soup = BeautifulSoup(s, "html5lib")
tags = soup.find_all(text=re.compile(r'pear'))
print tags
# [u'pearTYysnMXMUc', u'udv5NZQdpzpearz5a4oS85mD']

This sets up the dom and finds all tags where your text matches the regex pear (looking for "pear" literally).
See a demo on ideone.com.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...