VOOZH about

URL: https://www.geeksforgeeks.org/python/python-regex-split/

⇱ Python - Regex split() - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Regex split()

Last Updated : 18 Apr, 2025

re.split() method in Python is generally used to split a string by a specified pattern. Its working is similar to the standard split() function but adds more functionality. Let’s start with a simple example of re.split() method:


Output
['Geeks', 'for', 'Geeks']

Syntax of re.split() method

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

Parameters:

  • pattern (required): This regular expression pattern that defines where the string should be split.
  • string (required): This input string to be split based on the given pattern.
  • maxsplit (optional, default is 0): This maximum number of splits to perform; 0 means no limit.

Return Type: This re.split() method returns a list of strings.

Examples of python regex split() function

Splitting a String by Comma in Python

re.split() function from the re module is used when you need more flexibility, such as handling multiple spaces or other delimiters.


Output
['Geeks', 'for', 'Geeks']

Explanation:

  • This regex \W+ splits the string at non-word characters.
  • Since there are none in the sentence, it returns a list of words.

Splitting Strings with a Maximum Number of Splits

We can use re.split() from the re module to split a string with a regular expression and specify a maximum number of splits using the maxsplit parameter.


Output
['Geeks', 'for', 'Geeks']

Explanation:

  • This splits the string s at spaces, limiting the splits to a maximum of 2.

Splitting a String with Capturing Groups

This splits the string at the specified delimiters (comma and semicolon), but because of the capturing group, the delimiters themselves are retained in the output list.


Output
['Geeks', ',', ' for', ';', ' Geeks']
Comment
Article Tags: