Character classes
Master character classes: build sets of allowed characters, sweep whole ranges, flip a set inside-out with negation, and lean on the shorthands every hunter knows by heart.
Read the rules: Character classes in the Guide →Drill it: Character castles →
Builds on Hunter basics
What you'll learn
Steps · 13
- 01One slot, many choicesBriefing
- 02Character setsHunt
- 03Ranges: a-zHunt
- 04Ranges: 0-9Hunt
- 05Negated setsHunt
- 06Shorthand: \dHunt
- 07The shorthand trioExample
- 08Negated shorthandsHunt
- 09Metacharacters go literalHunt
- 10Combined rangesHunt
- 11Uppercase rangeHunt
- 12Golf: shortest catchHunt
- 13Slots masteredBriefing
Regex character classes, ranges and shorthands
A character class lets one slot in a pattern accept a choice of characters. Write the options inside square brackets and the class matches any single one of them. gr[ae]y accepts both spellings of the colour, because the slot after gr may be an a or an e. Classes are how you say "a vowel here" or "some digit there" without writing out every possible word.
Classes get more useful with ranges and negation. A hyphen between two characters covers everything in between, so [1-5] is any digit from one to five and [A-Za-z] is any plain letter. A caret right after the opening bracket flips the set: [^,] is any character except a comma. Whatever is inside, a class always uses up exactly one character.
Some sets come up so often that regex gives them shorthands. \d is a digit, \w is a word character (letter, digit or underscore) and \s is whitespace. Their capital forms \D, \W and \S mean the opposite. Reach for a class whenever a hunt says "any of these" or "anything but these" for a single position.
Examples
Catches
- gray
- grey
- greyhound
Spares
- groan
- grid
The class offers two choices for the third letter and nothing else.
Catches
- 1star
- 5stars
- my3star
Spares
- 6star
- 0star
- star
A range covers every digit from 1 to 5 in one slot.
Catches
- zap
- lazy
- ozone
Spares
- buzz
- fizz
- quiz
A negated class still needs a character, so a z at the very end doesn't match, and neither does a z followed by another z.
Catches
- 1 2
- room 4 5
Spares
- 12
- 1-2
Shorthands combine like letters: a digit, a space, then another digit.
Common mistakes
- Reading a class as a word.
[cat]matches one c, a or t, not the wordcat, so it also catchesteaandact. - Writing ranges that cross cases.
[a-Z]is an error in JavaScript, and[A-z]quietly lets in symbols such as[,^and_; use[A-Za-z]. - Expecting
\wto cover accented letters. In JavaScript it means only ASCII letters, digits and underscore, so the é incafécounts as a non-word character.
Read the rules: Character classes in the Guide →Drill it: Character castles →
Read more: Regex character classes: \d, \w, \s, [a-z] and their traps →