Regular expressions are one of the most powerful tools a developer has, and one of the most error-prone. They power search-and-replace, validation, parsing and routing — but a pattern that looks right can silently match too much or nothing at all. This cheatsheet covers the building blocks you actually reach for, assembles them into useful patterns, and points out the traps that catch people most often.
The core building blocks
Almost every pattern is built from a small set of pieces. Character classes match a type of character, quantifiers say how many, anchors pin the match to a position, and groups capture or organise parts of the match.
- Character classes: \d (digit), \w (word character), \s (whitespace), . (any character), and [abc] (any of a, b, c).
- Quantifiers: * (zero or more), + (one or more), ? (zero or one), {2,4} (between two and four).
- Anchors: ^ (start), $ (end), \b (word boundary).
- Groups: (…) captures, (?:…) groups without capturing, | means OR.
Patterns you will reuse
- Digits only: ^\d+$
- A simple email shape: ^[\w.+-]+@[\w-]+\.[\w.-]+$
- A hex color: ^#?[0-9a-fA-F]{6}$
- Leading/trailing whitespace: ^\s+|\s+$
- A slug: ^[a-z0-9]+(?:-[a-z0-9]+)*$
Treat these as starting points, not gospel — validation rules like email are famously hard to capture perfectly, and a looser pattern plus a real send-test often beats an over-strict one.
The mistakes that bite
Greedy quantifiers are the classic trap: by default + and * match as much as possible, so .* will happily swallow far more than you intended. Add a ? to make them lazy (.*?). Forgetting to anchor a validation pattern is another: without ^ and $, your pattern can match a substring and pass input you meant to reject. And remember that flags change everything — the g flag finds all matches, i ignores case, and m changes what ^ and $ mean.
Test against real data
The single best habit with regex is to test against real examples — including the ones that should NOT match — before trusting a pattern in code. A live tester that highlights matches and capture groups turns regex from guesswork into something you can verify in seconds.