Python re.split() Method
re.split()is Pythonreused in the module forsplitting strings with regular expressionsfunction.
It splits the string according to the matched pattern and returns a list.
Word Definitions: split 是分割、 Split 的意思。
Basic Syntax and Parameters
Syntax Format
re.split(pattern, string, maxsplit=0, flags=0)
Parameter Description
- pattern: The regular expression used for splitting
- string: The string to be split
- maxsplit: Maximum number of splits, 0 means unlimited
- flags: Regular expression flags
Function Description
- Return Value: Returns a list of strings.
Examples
Example 1: Split by Space
Example
import re
text = "Python Java JavaScript"
# Split by space
result = re.split(r' ', text)
print(result)
text = "Python Java JavaScript"
# Split by space
result = re.split(r' ', text)
print(result)
Expected output:
['Python', 'Java', 'JavaScript']
Example 2: Split by Comma (Handling Multiple Delimiters)
Example
import re
text = "apple,banana;orange|grape"
# Split by comma, semicolon, and vertical bar
result = re.split(r'[,;|]', text)
print(result)
text = "apple,banana;orange|grape"
# Split by comma, semicolon, and vertical bar
result = re.split(r'[,;|]', text)
print(result)
Expected output:
['apple', 'banana', 'orange', 'grape']
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)
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)
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 a capturing group to keep the delimiters
result = re.split(r'(\d)', text)
print(result)
text = "a1b2c3"
# Use a capturing group to keep the delimiters
result = re.split(r'(\d)', text)
print(result)
Expected output:
['a', '1', 'b', '2', 'c', '3', '']
Other Extensions