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 get all matches from a regex in Python?
- How to match the beginning of a line with Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a URL path using Python regex?
- How to match a UUID using Python regex?
- How to match one or more occurence in Python regex?
- How to match zero or one occurence in Python regex?
- How to use negative lookbehind in Python regex?
- How to get a group from a regex in Python?
See more codes...