python-regexHow to match whitespace in Python regex?
To match whitespace in Python regex, use the \s
character class. This character class matches any whitespace character, including spaces, tabs, and line breaks.
Example code
import re
text = "This is a test string"
pattern = re.compile(r"\s")
matches = pattern.finditer(text)
for match in matches:
print(match)
Output example
<re.Match object; span=(4, 5), match=' '>
<re.Match object; span=(9, 10), match=' '>
Code explanation
import re
: imports there
module, which contains the functions needed to work with regular expressionstext = "This is a test string"
: creates a string to use for testingpattern = re.compile(r"\s")
: creates a regular expression pattern that matches any whitespace charactermatches = pattern.finditer(text)
: finds all matches of the pattern in the textfor match in matches:
: iterates over all matchesprint(match)
: prints out each match
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 use word boundaries in Python Regex?
- How to match a UUID using Python regex?
- How to remove numbers from a string using Python regex?
- How to get all matches from a regex in Python?
- How to ignore case in Python regex?
- How to match a URL path using Python regex?
- How to perform a zero length match with Python Regex?
See more codes...