Python re.split() - Split String using Regular Expression


Python re.split() Function

re.split() function splits the given string at the occurrences of the specified pattern. The search for pattern happens from left to right.

In this tutorial, we will learn how to use re.split() function with the help of example programs.

Syntax - re.split()

The syntax of re.split() function is

re.split(pattern, string, maxsplit=0, flags=0)

where

ParameterDescription
pattern[Mandatory] The pattern which has to be found in the string.
string[Mandatory] The string in which the pattern has to be found.
maxsplit[Optional] The maximum limit on number of splits re.split() shall do.
flags[Optional] Optional flags like re.IGNORECASE, etc.

Return Value

The function returns a List object.

Example 1: re.split()

In this example, we will take a pattern and a string; and split the string at every match for the pattern in the string using re.split() function.

Python Program

import re

pattern = '-+'
string = '2344------HELLO--WORLD'
result = re.split(pattern, string)
print(result)

Output

['2344', 'HELLO', 'WORLD']

Example 2: re.split() - Split String by Space

In this example, we will take a string and split it with space as delimiter using re.split() function. The pattern \s+ matches one or more adjacent spaces.

Python Program

import re

pattern = '\s+'
string = 'Today   is a   present'
result = re.split(pattern, string)
print(result)

Output

['Today', 'is', 'a', 'present']

Example 3: re.split() - No Matches

If there is no matching for the pattern in the string, re.split() returns the string as sole element in the list returned.

Python Program

import re

pattern = '\s+'
string = 'HelloWorld'
result = re.split(pattern, string)
print(result)

Output

['HelloWorld']

Example 4: re.split() - Maximum Number of Splits

We can also limit the maximum number of splits done by re.split() function.

In this example, we split a string at pattern matchings using re.split(), but limit the number of splits by specifying maxsplit parameter.

Python Program

import re

pattern = '\s+'
string = 'Today is a present.'
result = re.split(pattern, string, maxsplit=2)
print(result)

Output

['Today', 'is', 'a present.']

The output contains three items because the given string is split at only two places as specified by maxsplit.

Summary

In this tutorial of Python Examples, we learned how to use re.split() function to split a given string at specified pattern matchings, with the help of example programs.