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 question mark in Python regex?
- How to match a UUID using Python regex?
- How to regex match excluding a word in Python?
- How to match a year with Python Regex?
- How to validate an IP using Python regex?
- How to replace all using Python regex?
- How to replace a certain group using Python regex?
- How to match zero or one occurence in Python regex?
- How to ignore case in Python regex?
See more codes...