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 there
module, 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 stringstring
into 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 replace all using Python regex?
- How to count matches 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 YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...