Python Regex re.split

By Xah Lee. Date: . Last updated: .
re.split(regex, text)
Returns a list of splitted string with regex as boundary.
import re

print(re.split(r' +', 'what   do  you think'))
# ['what', 'do', 'you', 'think']

If the boundary pattern is enclosed in parenthesis, then it is included in the returned list.

import re

print(re.split(r'( +)', 'what   do  you think'))
# ['what', '   ', 'do', '  ', 'you', ' ', 'think']

If there are more than one capturing parenthesis in pattern, they are all included in the returned list in sequence.

import re

print(re.split(r'( +)(@+)', 'what   @@do  @@you @@think'))
# ['what', '   ', '@@', 'do', '  ', '@@', 'you', ' ', '@@', 'think']
re.split(regex, text, maxsplit = n)
Split, at most n times.
import re
print(re.split(r' ', 'a b c d e', maxsplit = 2))
# ['a', 'b', 'c d e']

Python Regex Functions

Python Regular Expression