8. Character sets
A character set [...] matches one character from a list:
- Inside
[ ], characters are alternatives; the set matches exactly one of them. -between two characters defines a range:[a-c]isa,borc.- A leading
^negates the set: it matches any character that is not listed. - Inside a set, most metacharacters lose their special meaning:
.is a literal dot, and-at the start or end is a literal hyphen. - Quantifiers still apply outside the brackets:
[aeiou]+matches one or more vowels.
Coming from JavaScript? the syntax is the same. The difference is Unicode: Python \w matches Unicode letters by default, while JS \w stays ASCII-only.
Match one vowel
A set matches one character from its list. Use r"[aeiou]" on "Hola mundo" and print every match.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use a range
[a-c] is shorthand for [abc]. Use the range r"[a-c]" on "abc123" and print the matches.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Combine a set with literal text
A set can be one part of a longer pattern. Use r"[mfb]an" on "man ran fan ñan ban" and print the matches. Only words starting with m, f or b match.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Negate a set
A leading ^ inside the brackets negates the set. Use r"[^aeiou]" on "Hola" and print the matches: consonants only.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Negate a range
A negated range matches anything outside the range. Use r"[^a-z]" on "abc 123" and print the matches: the space and the digits.
Print exactly:
Create a free account to save your progress and unlock chapter 2.