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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With