Hone

Lessons · Regex · split: keeping the separator

Splitting, and keeping what you split on

A capturing group in the split pattern puts the separator into the result; without the brackets it is thrown away.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Rebuilding the text after changing the pieces needs the separators. So does knowing which of several separators was used.

How to think about it

Decide whether the separator is data. If it is, capture it. There is no flag for this: the brackets are the switch.

Worked example

re.split(r',', 'a,b,c')
The separators are gone.
re.split(r'(,)', 'a,b,c')
Captured, so they come back too.
re.split(r'\s*,\s*', 'a , b,c')
A pattern can absorb the space around a separator, which str.split cannot.

Your turn

Split on the commas and keep them in the result.

re.split(r'', 'a,b,c')

The trap

A pattern that can match nothing splits between every character. re.split(r'x*', 'abc') is not what anybody wants.

Practise split: keeping the separator on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.