Lesson 03
Character Classes — Brackets, Ranges, and a Caret
Write Python regex character classes with brackets, ranges, and a leading caret to keep letters, digits, or everything else.
A character class matches one character from a set you write inside brackets. A caret just after the opening bracket flips the set.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
[abc], ranges, and[^...]- Letters, digits, and the combinations of both
- Why a class without a quantifier matches one character at a time
The picture
Square brackets mean "one of these." They do not mean "this whole word" until a later lesson adds a quantifier.
| Pattern | Matches one character that is |
|---|---|
[abc] |
a or b or c |
[^abc] |
anything except a, b, or c |
[A-Z] |
an uppercase letter |
[^A-Z] |
not an uppercase letter |
[a-z] |
a lowercase letter |
[^a-z] |
not a lowercase letter |
[0-9] |
a digit |
[^0-9] |
not a digit |
[A-Za-z] |
any letter |
[^A-Za-z] |
not a letter |
[A-Za-z0-9] |
a letter or a digit |
[^A-Za-z0-9] |
a symbol, not a letter or digit |
[A-Z0-9] |
uppercase or a digit |
[a-z0-9] |
lowercase or a digit |
The caret is special only when it is the first character inside the brackets. A hyphen between two characters is a range. Put a hyphen at the start or end of the brackets if you mean a literal hyphen.
findall with [a-z] returns each lowercase letter separately. very from Avery is four matches, not one word. The quantifier lesson is what glues them together.
Example
import re
text = "Avery-7!"
print(re.findall(r"[A-Z]", text))
print(re.findall(r"[a-z]", text))
print(re.findall(r"[0-9]", text))
print(re.findall(r"[^A-Za-z0-9]", text))You should see the uppercase A, then each lowercase letter, then 7, then the hyphen and the exclamation mark. Those last two are the characters the final class keeps.
Key takeaways
-
Brackets match one character from a set
-
A range such as
[0-9]or[A-Z]covers that span -
[^...]matches a character outside the set -
Without a quantifier, each match is a single character
-
Next: Predefined Classes —
\d,\w, and\s -
Previous: re Functions
Loading playground…
Check your understanding
Character classes quiz
[abc] matches:
1 / 10