简体   繁体   中英

Regular expression to return list in Python?

So, I'm wanting to make a list in Python from a large chunk of HTML code, but I'm trying to split it up based on the HTML tags. I'm not well versed in regular expressions so I don't know how to go about this. For instance, let's say I had this piece of HTML code:

<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>

I would like for me to be able to save this code (albeit a much bigger version of it) into a string, and then use a function to return a list like this:

list = ["Example text here", "Example text here", "Example text here"]

Anyway I can do this?

I agree with @roippi's comment, please use HTML parser. However, if you really want to use regex, the following is what you want:

import re

s = '<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>'

>>> print re.findall(r'>\s*([^<]+?)\s*<', s)
['Example text here', 'Example text here', 'Example text here']

You could simply use BeautifulSoup for this purpose.

import bs4

html = '''
<option value="674"> Example text here </option>
<option value="673"> Example text here</option>
<option value="672"> Example text here </option>
'''

soup  = bs4.BeautifulSoup(html)
mylst = [str(x.text).strip() for x in soup.find_all('option')]

Output

['Example text here', 'Example text here', 'Example text here']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM