104
votes

This code almost does what I need it to..

for line in all_lines:
    s = line.split('>')

Except it removes all the '>' delimiters.

So,

<html><head>

Turns into

['<html','<head']

Is there a way to use the split() method but keep the delimiter, instead of removing it?

With these results..

['<html>','<head>']
4
This doesn't really answer your question, but if you're trying to parse HTML in Python, I highly recommend Beautiful Soup.Michael Mior
This question should be reopened. The duplicate one is regex-specific.orestisf
@orestisf Also, the "duplicate" one answers a different problem. ['<html', '>', '<head', '>', ''] is different from ['<html>', '<head>']. I know it's been a few months but I just voted to reopen. If you do too someone else make take it over the finish line?user1717828
re.split(r"(?<=>(?!$))", '<html><head>') directly gives the answer. This way it can be handled by playing with regex look-aroundsDhananjay_Goratela

4 Answers

61
votes
d = ">"
for line in all_lines:
    s =  [e+d for e in line.split(d) if e]
36
votes

If you are parsing HTML with splits, you are most likely doing it wrong, except if you are writing a one-shot script aimed at a fixed and secure content file. If it is supposed to work on any HTML input, how will you handle something like <a title='growth > 8%' href='#something'>?

Anyway, the following works for me:

>>> import re
>>> re.split('(<[^>]*>)', '<body><table><tr><td>')[1::2]
['<body>', '<table>', '<tr>', '<td>']
20
votes

How about this:

import re
s = '<html><head>'
re.findall('[^>]+>', s)
0
votes

Just split it, then for each element in the array/list (apart from the last one) add a trailing ">" to it.