SyntaxStudy
Sign Up
Python Beginner 3 min read

Character Classes

Character Classes

Square brackets define a set of characters to match. Ranges like [a-z], negation [^...], and shortcuts like \d, \w, \s.

Example
import re

# \d = digit, \w = word char, \s = whitespace
print(re.findall(r"\d+", "abc 123 def 456"))  # ["123", "456"]
print(re.findall(r"\w+", "hello world!"))     # ["hello", "world"]
print(re.findall(r"\S+", "a b  c"))           # ["a", "b", "c"]
Pro Tip

Capital versions are negations: \D = non-digit, \W = non-word, \S = non-space.