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 replace all using Python regex?
- How to match a hex number with regex in Python?
- How to remove special characters using Python regex?
- How to get a group from a regex in Python?
- How to replace in a file using Python regex?
- How to make a case insensitive match with Python regex?
- How to validate an IP using Python regex?
- How to perform a zero length match with Python Regex?
- How to ignore case in Python regex?
See more codes...