Regex Character Classes, Quantifiers & Anchors
Most regular expressions are built from three kinds of piece: what to match (character classes), how many (quantifiers), and where (anchors). Master these and the rest of regex is mostly combination.
This is a supporting guide in The Complete Guide to Regular Expressions.
Character classes
A character class matches exactly one character from a set:
[abc]— an a, b, or c[a-z],[A-Z],[0-9]— ranges[a-zA-Z0-9_]— combine ranges and characters[^...]— negate:[^0-9]is any non-digit
Inside a class most metacharacters lose their special meaning — [.] matches a literal dot, no escaping needed. The characters that still matter inside a class are ^ (only first), - (a range unless first/last), and ].
Shorthand classes
Common sets have shortcuts you'll use constantly:
| Shorthand | Matches | Equivalent |
|---|---|---|
\d | a digit | [0-9] |
\w | a word char | [A-Za-z0-9_] |
\s | whitespace | space, tab, newline |
\D \W \S | the negations | not the above |
Quantifiers
Quantifiers repeat the item just before them:
*— zero or more+— one or more?— zero or one (optional){3}— exactly three{2,5}— between two and five{2,}— two or more
Greedy vs lazy
By default quantifiers are greedy: they match as much as they can, then give back if needed. Add ? to make them lazy (match as little as possible). The classic example is matching inside tags:
Input: <b>one</b><b>two</b>
<.+> -> matches the whole line (greedy)
<.+?> -> matches <b> then </b> ... (lazy, each tag)
Reaching for lazy quantifiers is often the fix when a pattern "matches too much".
Anchors and boundaries
Anchors match a position between characters, not a character itself:
^— start of the string (or line, with themflag)$— end of the string (or line)\b— a word boundary (between\wand non-\w)\B— not a word boundary
^\d{3}-\d{4}$ means "the entire string is 3 digits, a dash, then 4 digits" — the anchors are what stop it from matching that pattern inside a longer string.
Related
Part of The Complete Guide to Regular Expressions. See also Groups, Backreferences & Lookarounds.
Try it
Test these against real text in the Regex Tester — matches highlight live as you type, all in your browser.