Classes are how a pattern says 'a digit here, a letter there', the core of almost every useful regex.
A character class in square brackets matches exactly one character from a set:
[aeiou]one vowel;[a-z]a range;[A-Za-z0-9_]several ranges together.[^0-9]a negated class: any character except a digit (including newline).- Inside a class,
^is special only at the start,-only between two characters (put it first or last to mean a literal hyphen), and]must be escaped or come first.
Shorthand classes save typing:
\ddigit,\wword character (letters, digits, underscore),\swhitespace (space, tab, newline...).- Upper-case versions negate them:
\D,\W,\S. .matches any character except newline (unless the dotall flag is on).
In Python 3 and in JavaScript with the u or v flag, \d and \w can match more than ASCII: Python's \d matches any Unicode decimal digit such as Arabic-Indic digits. Use [0-9] (or Python's re.ASCII flag) when you mean only ASCII digits, for example when validating numeric input.
POSIX tools such as grep and sed use bracket expressions like [[:digit:]] and [[:space:]] instead of the backslash shorthands.
Example
import re
text = "Room 101, floor 3; code A-7_x"
print(re.findall(r"\d", text)) # ['1', '0', '1', '3', '7']
print(re.findall(r"[A-Z]", text)) # ['R', 'A']
print(re.findall(r"[^a-z0-9 ]", text)) # ['R', ',', ';', 'A', '-', '_']
print(re.findall(r"[-_]", text)) # ['-', '_'] hyphen first = literal
print(re.findall(r"\s", "a b\tc")) # [' ', '\t']
print(re.findall(r"\d", "٣ and 3")) # ['٣', '3'] Unicode digit
print(re.findall(r"\d", "٣ and 3", re.ASCII)) # ['3']
print(re.findall(r"[0-9]", "٣ and 3")) # ['3']Remember
- [...] matches exactly one character from the set; [^...] negates it
- \d \w \s and their negations \D \W \S are shorthand classes
- . matches anything except newline by default
Watch out for
- Writing [a-Z] or [A-z]: the second also includes [ \ ] ^ _ and backtick, which sit between Z and a.