Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into html tags using python regex?

Tags:

python

regex

Say I have a string:

"<blockquote>Quote</blockquote><br />text <h3>This is a title</h3>"

Expected Output:

["<blockquote>Quote</blockquote><br />", "text", "<h3>This is a title</h3>"]

I need both the opening and closing tags to be included in the same item, as above.

I've tried: re.split("<*>*</*>", s)

I'm quite new with Regex so any help is appreciated

like image 910
kpaul Avatar asked Apr 19 '26 06:04

kpaul


1 Answers

You can use re.findall to do this.

import re
s = "<blockquote>Quote</blockquote><br />text <h3>This is a title</h3>"
re.findall(r'<[^>]*>.*?</[^>]*>(?:<[^>]*/>)?|[^<>]+', s)
# ['<blockquote>Quote</blockquote><br />', 'text ', '<h3>This is a title</h3>']

But avoid parsing html data like directly using regex and consider using something like BeautifulSoup

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(s, "html.parser")
>>> soup.findAll()
[<blockquote>Quote</blockquote>, <br/>, <h3>This is a title</h3>]
>>> soup.findAll()[0].text
'Quote'
>>> [s for s in soup.strings]
['Quote', 'text ', 'This is a title']
like image 200
Sunitha Avatar answered Apr 20 '26 20:04

Sunitha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!