python-regexHow to split using Python regex?
Python's re module provides a powerful set of tools for working with regular expressions. The re.split() function can be used to split a string into a list of substrings based on a regular expression pattern.
import re
string = "This is a string to split"
result = re.split("\s+", string)
print(result)
Output example
['This', 'is', 'a', 'string', 'to', 'split']
The code above uses the re.split() function to split the string "This is a string to split" into a list of substrings based on the regular expression pattern \s+, which matches one or more whitespace characters.
Parts of the code:
import re: imports theremodule, which provides tools for working with regular expressions.string = "This is a string to split": assigns the string to be split to the variablestring.re.split("\s+", string): uses there.split()function to split the stringstringinto a list of substrings based on the regular expression pattern\s+, which matches one or more whitespace characters.print(result): prints the resulting list of substrings.
Helpful links
More of Python Regex
- How to use word boundaries in Python Regex?
- How to use named groups with regex in Python?
- How to perform a zero length match with Python Regex?
- How to match a question mark in Python regex?
- How to match a plus sign in Python regex?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match HTML tags with regex in Python?
- How to use quantifiers in Python regex?
- How to match any symbol except a given one with Python regex?
See more codes...