How to use re.split() in Python

Regex, or regular expression, is a string of characters that defines a search pattern. It offers a refined technique to match and edit text based on specific patterns or rules.

Python has a module named re that provides methods for working with regular expressions.

The re.split() function

The re.split() method in Python splits a text based on a regular expression pattern. It divides the text and returns a list of substrings wherever the pattern matches.

The general syntax for using re.split() is given below:

Syntax

re.split(pattern, string, maxsplit=0, flags=0)
Syntax for re.split()
  • pattern: The pattern used to split the string.

  • string: The input string to be split.

  • maxsplit (optional): The maximum number of splits to execute. The default is 0, which means all possible splits.

  • flags (optional): Additional flags to change the pattern’s behavior.

Code example

You can find an example of how to use re.split() Python.

import re
string = "Hello, there!Welcome to educative"
pattern = r"[, !]" # Split on comma, space, or exclamation mark
result = re.split(pattern, string)
print(result)

Code explanation

Line 1: In this line, we import the re module, which provides functions for working with regular expressions in Python.

Line 4: Next, we assign the regular expression pattern "[, !]" to the variable pattern. The pattern specifies a character class that matches a comma, space, or exclamation mark. These characters will be used as separators for splitting the string.

Line 6: Moving on, we use the re.split() function to split the string using the pattern. It returns a list of substrings, and the resulting list is assigned to the variable result.

Line 7: Lastly, this line prints the result list, which contains the substrings obtained from splitting the string.

This indicates that the string has been successfully split into substrings based on the specified pattern, and the resulting substrings are stored in the result list.

You may efficiently deal with regular expressions in Python and change text based on specific patterns or rules by exploiting the re module's methods.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved