Regex Syntax Cheat Sheet
Regular expressions match patterns in text. Ninety percent of practical regex is built from the two dozen tokens below.
Core tokens
| Token | Matches | Example |
|---|---|---|
| . | Any character except newline | a.c → abc, a1c |
| \d \D | Digit / non-digit | \d\d → 42 |
| \w \W | Word char [A-Za-z0-9_] / non-word | \w+ → hello_1 |
| \s \S | Whitespace / non-whitespace | a\sb → a b |
| ^ $ | Start / end of string (or line with m flag) | ^Hi → Hi there |
| \b | Word boundary | \bcat\b → cat, not category |
Quantifiers
| Token | Meaning | Example |
|---|---|---|
| * | 0 or more | ab*c → ac, abc, abbc |
| + | 1 or more | ab+c → abc, abbc |
| ? | 0 or 1 (optional) | colou?r → color, colour |
| {n} | Exactly n times | \d{4} → 2026 |
| {n,} {n,m} | n or more / between n and m | \d{2,4} → 12, 123, 1234 |
| *? +? ?? | Lazy versions (match as little as possible) | <.+?> → first tag only |
Groups, classes, lookarounds
| Token | Meaning | Example |
|---|---|---|
| [abc] [a-z] | Character class (any listed char / range) | [aeiou] → vowels |
| [^abc] | Negated class (anything but) | [^0-9] → non-digits |
| (abc) | Capturing group | (\d{4})-(\d{2}) → year, month |
| (?:abc) | Non-capturing group | (?:https?|ftp):// |
| a|b | Alternation (or) | cat|dog |
| (?=…) (?!…) | Lookahead / negative lookahead | \d+(?=px) → 16 in "16px" |
| (?<=…) (? | Lookbehind / negative lookbehind | (?<=\$)\d+ → 16 in "$16" |
Flags
| Flag | Meaning |
|---|---|
| g | Global — find all matches, not just the first |
| i | Case-insensitive |
| m | ^ and $ match line starts/ends |
| s | Dot also matches newlines |
| u | Full Unicode support |
FAQ
Greedy vs lazy — when do I care?
Quantifiers are greedy by default: <.+> swallows bold whole. Add ? (<.+?>) to stop at the first closing bracket. Rule of thumb: parsing-ish tasks want lazy quantifiers.
Why does my regex match inside longer words?
You need boundaries: \bcat\b matches "cat" but not "category". Boundaries are zero-width — they assert position without consuming characters.
Can regex parse HTML?
Badly and briefly. Regex cannot track nesting; anything tree-shaped needs a real parser. Use regex for flat-text validation, extraction, and replacement.
Try it instead of memorizing it
Test it live in the Regex Tester