C.W.K.
Stream
Lesson 03 of 12 · published

Character Classes [abc] — Picking from a Set

~8 min · character-class, brackets

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Square brackets: pick one from this list

[abc] matches exactly one character that is either a, b, or c. Not the whole substring abc — one character that's one of those three.

This is the workhorse of regex. "A vowel": [aeiou]. "A digit or a letter": [a-zA-Z0-9]. "A separator": [ ,;\t]. Once you start thinking in character classes, half the patterns you write fall out naturally.

Inside a class, special characters mostly aren't special

One of the most useful regex facts: most metacharacters lose their special meaning inside [...]. The dot . inside a class is literal. So is +, ?, (, ), {, }. Inside a class you barely need to escape anything.

The exceptions — characters that ARE still special inside a class:

  • ] — closes the class. Escape it (\]) or place it first ([]abc]).
  • \ — still the escape character.
  • ^ — special if it's the first character (negation, next lesson). Literal anywhere else.
  • - — special between two characters (forms a range). Literal if first, last, or escaped.

Order doesn't matter, duplicates are harmless

[cba] is identical to [abc]. [aabbcc] is identical to [abc]. The class is a set — engine deduplicates internally.

Code

Character class basics·python
import re

# 'A vowel'
re.findall(r'[aeiou]', 'hello world')
# ['e', 'o', 'o']

# Hex digit (one character)
re.findall(r'[0-9a-fA-F]', '#FF8FBE')
# ['F', 'F', '8', 'F', 'B', 'E']

# Inside a class, dot is literal
re.findall(r'[.,;]', 'Hi, world; ok.')
# [',', ';', '.']

# To include ']' in a class, escape it or put it first
re.findall(r'[][]', '[1] [2] [3]')  # matches '[' or ']'
# ['[', ']', '[', ']', '[', ']']

External links

Exercise

Write one character class that matches any single character a phone number could contain: digits, plus, hyphen, parentheses, space. No alternation. Test it against +1 (415) 555-0199 and confirm every character matches one at a time.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.