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 match a YYYY-MM-DD date with Python Regex?
- How to match a year with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a UUID using Python regex?
- How to match a URL using Python regex?
- How to match a float with regex in Python?
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
- How to match whitespace in Python regex?
- How to match a plus sign in Python regex?
See more codes...