Learn · Cheat sheet
Regex Cheat Sheet for Everyday Code
The twenty patterns and flags that cover most real-world matching, with copy-paste examples.
Character classes
| Pattern | Matches |
|---|---|
\d |
a digit (0-9) |
\w |
a word character (A-Za-z0-9_) |
\s |
whitespace |
. |
any char except newline (with s flag: any char) |
[abc] |
any one of a, b, c |
[^abc] |
anything except those |
Quantifiers
| Pattern | Meaning |
|---|---|
a* |
zero or more |
a+ |
one or more |
a? |
zero or one |
a{2,4} |
between two and four |
a{2,} |
two or more |
Groups & alternation
(abc)— capture group ($1,$2… in replacement).(?:abc)— non-capturing group.a|b— alternation ("a or b").(?<name>…)— named group.
Anchors & boundaries
^start of string (withm: start of line).$end of string (withm: end of line).\bword boundary —\bcat\bmatches "cat" but not "category".
Flags
g— global (find all, needed formatchAll).i— case-insensitive.m— multiline (^/$act per line).s— dot matches newlines.u— unicode mode (enables\p{…}).
Everyday patterns
| Job | Pattern |
|---|---|
| Email (practical) | ^[^\s@]+@[^\s@]+\.[^\s@]+$ |
Date YYYY-MM-DD |
^\d{4}-\d{2}-\d{2}$ |
| Slug | ^[a-z0-9]+(?:-[a-z0-9]+)*$ |
| Hex color | ^#?[0-9a-fA-F]{6}$ |
| Leading/trailing space | `^\s+ |
| Extract numbers | \d+ with g |
Replacing with groups
"2026-09-09".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")
// "09/09/2026"
Greedy vs lazy
Quantifiers are greedy by default: a.+b against a1b2b matches the whole a1b2b, taking the last possible b. Add ? to make it lazy — a.+?b matches the shortest, a1b. When you find a pattern matching too much, suspect greed before suspecting your character class.
Common mistakes
- Forgetting the
gflag."aaa".match(/a/)returns one match; withgit returns all three. Tools and languages often behave differently here. - Unescaped dots.
.matches any character. To match a literal dot in a domain or file name, write\.. - Anchors that are too loose.
/\d{4}/matches anywhere in the string. Wrap with^…$for a full-match check. - Catastrophic backtracking. Nested quantifiers like
(a+)+on long strings can freeze the page. Keep nesting shallow, and test on worst-case input in the regex tester before deploying it in validation hot paths.
Practice it
Test every pattern above in ToolsKit's regex tester before you trust it in code. Build the pattern against the real samples you will validate, not just the happy path — one tricky input is worth ten clean ones.