← Cheat Sheets

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

TokenMatchesExample
.Any character except newlinea.c → abc, a1c
\d \DDigit / non-digit\d\d → 42
\w \WWord char [A-Za-z0-9_] / non-word\w+ → hello_1
\s \SWhitespace / non-whitespacea\sb → a b
^ $Start / end of string (or line with m flag)^Hi → Hi there
\bWord boundary\bcat\b → cat, not category

Quantifiers

TokenMeaningExample
*0 or moreab*c → ac, abc, abbc
+1 or moreab+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

TokenMeaningExample
[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|bAlternation (or)cat|dog
(?=…) (?!…)Lookahead / negative lookahead\d+(?=px) → 16 in "16px"
(?<=…) (?Lookbehind / negative lookbehind(?<=\$)\d+ → 16 in "$16"

Flags

FlagMeaning
gGlobal — find all matches, not just the first
iCase-insensitive
m^ and $ match line starts/ends
sDot also matches newlines
uFull 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