Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python re.split() Method

Python re.split() Method

Python re Module Python re Module


re.split() is a function in the Python re module used toSplit a string with a regular expression.

It splits the string according to the matched pattern and returns a list.

Word meaning: split 是分割、 Split 的意思。


Basic syntax and parameters

Syntax format

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

Parameter Description

Function description


Example

Example 1: split by spaces

Example

import re

text = "Python Java JavaScript"

# Split by spaces
result = re.split(r' ', text)

print(result)

Expected output:

['Python', 'Java', 'JavaScript']

Example 2: split by commas (handling multiple delimiters)

Example

import re

text = "Apple,Banana;Orange|Grape"

# Split by commas, semicolons and vertical bars
result = re.split(r'[,;|]', text)

print(result)

Expected output:

['苹果', '香蕉', '橙子', '葡萄']

Example 3: limit the number of splits

Example

import re

text = "a:b:c:d:e"

# Split at most 2 times
result = re.split(r':', text, maxsplit=2)

print(result)

Expected output:

['a', 'b', 'c:d:e']

Example 4: split by whitespace characters

Example

import re

text = "Python\tJava\nC++\rRuby"

# Split by any whitespace character
result = re.split(r'\s+', text)

print(result)

Expected output:

['Python', 'Java', 'C++', 'Ruby']

Example 5: keep the delimiters

Example

import re

text = "a1b2c3"

# Use capturing groups to keep the delimiters
result = re.split(r'(\d)', text)

print(result)

Expected output:

['a', '1', 'b', '2', 'c', '3', '']

Python re Module Python re Module