Reference · Regular expressions

re.split

signature
re.split(str, str, str | null=) -> list

What it does

The text cut at every match of a pattern, as a list of the pieces between the matches. The matches themselves are left out. Where the separator is plain text, split does the same without a pattern. The flags come last: "i", "m", "s".

Examples

print(re.split("a, b,c ,  d", "\\s*,\\s*"))print(re.split("a1b22c", "\\d+"))print(re.split("one\ntwo\r\nthree", "\\r?\\n"))print(re.split("k1=v1;k2=v2", "[;=]"))
output
["a", "b", "c", "d"]["a", "b", "c"]["one", "two", "three"]["k1", "v1", "k2", "v2"]

Edge cases

print(re.split(",a,,b,", ","), re.split("x", "x"))print(re.split("abc", "x"), re.split("", "x"))print(re.split("a1b", "(\\d)"), re.split("A-b_C", "[-_]", "i"))print(re.split("ab", ""), re.split("aaa", "a*"))print(re.split("añb", "ñ"))
output
["", "a", "", "b", ""] ["", ""]["abc"] [""]["a", "b"] ["A", "b", "C"]["", "a", "b", ""] ["", "", ""]["a", "b"]

Errors

A pattern that is not supported (lookaround, backreferences, \p{...}, a bad escape, a bad flag) is a runtime error, not an error value, as is a text that is not a string. See re.test for what a pattern may hold.

this one fails
print(re.split("abc", "(?!b)"))
output
line 1: `re.split`: lookahead and lookbehind ((?= (?! (?<= (?<!) are not supported
this one fails
print(re.split(42, ","))
output
line 1: `re.split` expects a str as argument 1, got int

Chaining

The text comes first in a pipeline, and the pieces go on to map or filter:

print("a  b   c" | re.split("\\s+") | map(upper))print("one, two,,three" | re.split("\\s*,\\s*") | filter((p) => p != ""))let [key, value] = re.split("name = Ann", "\\s*=\\s*")print(key, value)
output
["A", "B", "C"]["one", "two", "three"]name Ann

See also

split, re.find_all, re.replace, join, filter

Thread
6Useful? Like it, or add to its thread below.

Thread 0 posts

On re.split(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo