re.split
str.split for patterns. Capturing groups in the separator are kept in the result, and a separator at either end produces an empty string there. Also available as Pattern.split(string, maxsplit=0).
Demo
import re re.split('\\s*[,;|]\\s*', 'red , green;blue| alpha')
Leading or trailing separators produce empty strings — ',a,,b,' splits into five items, three of them empty. With a group, ([+-]), each operator appears between the numbers. The empty pattern matches between every character, so it splits 'abc' into single letters with an empty string at each end (allowed since Python 3.7).
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | str | re.Pattern | yes | The separator, as a raw-string regular expression. |
| string | str | yes | The text to split. |
| maxsplit | int | no (0) | At most this many splits; the rest stays in the last item. 0 = no limit. Pass by keyword (positional is deprecated since 3.13). |
| flags | re.RegexFlag | int | no (0) | Flags such as re.IGNORECASE. Pass by keyword. |
Return value
list[str | None] — The pieces between matches; with capturing groups, the group texts are inserted between them (None for groups that did not match).
Common patterns
import re parts = re.split(r'\s*[,;]\s*', line.strip())
import re tokens = [t for t in re.split(r'\s*([-+*/()])\s*', expr) if t]
import re lines = re.split(r'\r\n|\r|\n', text)
Examples
Pitfalls
import re re.split(r'\s+', ' a b ')
' a b '.split()
import re re.split(r'\s(and|or)\s', 'tea and cake or pie')
import re re.split(r'\s(?:and|or)\s', 'tea and cake or pie')
import re re.split(r'x', 'aXbxc', re.I)
import re re.split(r'x', 'aXbxc', flags=re.I)
When to use
- Separators that vary (several characters, optional spaces, words)
- Tokenizing while keeping the delimiters (capturing group)
- One fixed separator → str.split(sep)
- Whitespace → str.split() with no argument
- Lines → str.splitlines()
- CSV with quoted fields → the csv module
Notes
FAQ
re.split(r'[,;|]', text) — a character class lists single-character separators; use alternation for longer ones: re.split(r'\s*(?:and|or)\s*', text).