Character classes
Square brackets match one character from a set. Learn ranges, the few characters that change meaning inside brackets, and the ordering traps in [A-z] and [z-a].
Character classes
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- [abc] matches exactly one character, and that character must be a, b or c. It never matches two characters or none.
- A range like [a-f] means every character between the two ends by code point. [A-z] therefore also includes [ \ ] ^ _ and the backtick.
- Inside brackets only ^ (first), - (between two characters), ] and \ are special in JavaScript. A dot or dollar sign is already literal, so [.] needs no backslash.
- Put - first or last, or escape it, to match a literal dash. Reversed ranges such as [z-a] are a SyntaxError.
- POSIX brackets differ: a backslash is literal inside them, and a ] right after the opening bracket is a literal ]. In JavaScript [] is an empty class that never matches.
One slot, several allowed characters
The previous lessons matched fixed text. Real text varies by one character at a time: gray or grey, color or colour, a hex digit that could be any of sixteen. You could write gray|grey, but that repeats the whole word to vary a single letter. What you want to say is “a g, an r, an a or an e, then a y”.
A character class says that. Square brackets list the characters allowed in one position, and the engine matches exactly one of them:
"gray grey graay gry".match(/gr[ae]y/g) // [ 'gray', 'grey' ]
"cabbage".match(/[abc]/g) // [ 'c', 'a', 'b', 'b', 'a' ]
The first pattern skipped graay (two letters in the slot) and gry (none). The word to hold on to is one: [abc] consumes a single character. To get more, put a quantifier after it, which is the next group of lessons. The class is also not the same as (ab), which is a group needing the letters a then b:
/[ab]/.test("ab") // true (it found one of them)
/^[ab]$/.test("ab") // false (the whole string must be exactly one)
/^(ab)$/.test("ab") // true
Ranges
Typing sixteen hex digits is tedious, so a dash between two characters means “everything from here to there”. The engine goes by character code:
"id=3fa9 zz 07".match(/[a-f0-9]+/g) // [ 'd', '3fa9', '07' ]
"Ada Lovelace-1815".match(/[A-Za-z]+/g) // [ 'Ada', 'Lovelace' ]
"aBc".match(/[a-z]/g) // [ 'a', 'c' ]
You can mix ranges and single characters in one class. The last line shows that [a-z] does not include B: uppercase letters are different characters, with different codes.
The ordering gotchas
Because ranges go by code, the order matters in two ways. First, the ends must be in ascending order. Both of these fail at pattern-compile time:
[z-a] Range out of order in character class
[a-Z] Range out of order in character class
Second, [A-z] is legal and wrong. Z is code 90, [ is 91 and a is 97. The range sweeps through everything in between:
"a_Z[x".match(/[A-z]/g) // [ 'a', '_', 'Z', '[', 'x' ]
The _ and [ got picked up. For letters, write [A-Za-z]. Also note that [a-z] is ASCII only: /[a-z]/.test("é") printed false, and /[à-ÿ]/.test("é") printed true. Non-ASCII letters get their own lesson later in the roadmap.
What is special inside brackets
The metacharacters from literals and escaping mostly stop being special inside a class, since the class has its own small rules. Of those, ., $, * and friends are literal (a class of *+?(){}| matched every one of those characters in a*+?(){}|b): "a.b.c".match(/[.]/g) returned two dots, and /[$^]/g found both a dollar sign and a caret (the caret only means something as the first character, which is the next lesson).
What is left:
^as the first character negates the class.-between two characters makes a range. For a literal dash put it first, last or escape it. All three of[a\-z],[-az]and[az-]matcheda,-andzin"a-z b".\starts an escape.\dinside a class still means “digit”, and[\b]means a backspace character, not a word boundary. I confirmed/[\b]/.test("b")isfalse.]ends the class.
Two oddities in JavaScript. An empty [] is a valid class that matches nothing (/[]/.test("a") is false), and [^] matches everything, newline included. And /[\d-x]/ is accepted in the default mode, treating the dash as a literal, while with the u flag it throws Invalid character class. When a shorthand sits next to a dash, put the dash first or escape it.
POSIX brackets are different
The shell tools follow the POSIX rules, and those differ. A ] placed first is a literal, and a backslash is an ordinary character:
$ printf 'a]b\nab\n' | /usr/bin/grep -n '[]]'
1:a]b
$ echo 'a z \' | /usr/bin/grep -o '[a\-z]'
a
z
\
In the second command \-z was read as a range from backslash (code 92) to z (122), so the dash was not matched at all. Python’s re sided with POSIX on the first rule: re.findall(r"[]a]", "a]b") printed ['a', ']'], while JavaScript treats [] as empty. The fix is the usual one: put the dash first or last and keep brackets simple, and test in the engine you ship on. The flavors lesson explains why.
About the video
The Coding Train’s “2.3: Regular Expressions: Character Classes - Programming with Text” was published on 16 September 2016 and runs 14 minutes 22 seconds. Its description says the video explains character classes as “a way of matching a selection of characters in a regular expression”. It is part of Daniel Shiffman’s “Programming from A to Z” course at NYU’s ITP, and the series works with JavaScript functions according to the series description. The video has no chapters, and I couldn’t read a transcript, so I can’t confirm it covers ranges, the ordering traps or POSIX differences. The oddities in this lesson are my own additions. English per its title and description.
What I did not run
GNU grep, regex101, and the v flag’s nested-class syntax, which I left for the unicode lessons.
Next
You have been listing the characters you want. Often it is easier to list the ones you don’t: Negated classes.
Check yourself
What does /gr[ae]y/g find in 'gray grey graay gry'?
gray and grey. The class matches exactly one of a or e, so graay (two letters) and gry (none) fail.
Why is [A-z] a bad way to say 'any letter'?
Ranges run by code point, and between Z (90) and a (97) sit [ \ ] ^ _ and the backtick. The class matches those too. Write [A-Za-z].
How do you put a literal dash in a class?
Place it first or last, as in [-az] or [az-], or escape it as [a\-z]. Anywhere between two characters it forms a range.
What does [a\-z] match in macOS grep, and why does it differ from JavaScript?
It matches a, z and the backslash, because in POSIX brackets the backslash is a literal and \-z becomes a range from backslash to z. JavaScript treats \- as an escaped dash.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.