Regex cheatsheet

Every regex symbol on one page, described in plain English. Bookmark it, keep it next to your editor, and test any pattern live when in doubt.

Character classes

.Any character except newline (any at all with flag s)
\d \DDigit 0–9 / not a digit
\w \WWord char (letter, digit, _) / not a word char
\s \SWhitespace / not whitespace
[abc]One of a, b or c
[^abc]Any character except a, b, c
[a-z0-9]Character ranges
\p{L}Unicode letter (needs flag u)

Anchors & boundaries

^Start of string (start of line with flag m)
$End of string (end of line with flag m)
\bWord boundary — edge between \w and \W
\BNot a word boundary

Quantifiers

*0 or more (greedy)
+1 or more (greedy)
?0 or 1 — optional
{3}Exactly 3 times
{2,}2 or more times
{2,5}Between 2 and 5 times
*? +? ??Lazy versions — match as little as possible

Groups & references

(abc)Capturing group — saved as $1, $2…
(?:abc)Non-capturing group — grouping only
(?<name>abc)Named capturing group
\1Backreference to group 1
\k<name>Backreference to a named group
a|bAlternation — a OR b

Lookarounds

(?=abc)Lookahead — followed by abc (abc not consumed)
(?!abc)Negative lookahead — NOT followed by abc
(?<=abc)Lookbehind — preceded by abc
(?<!abc)Negative lookbehind — NOT preceded by abc

Flags

gGlobal — find all matches, not just the first
iIgnore case
mMultiline — ^ and $ match line starts/ends
sDotAll — . also matches newlines
uUnicode — proper surrogate pairs and \p{…}
ySticky — match exactly at lastIndex

The two mistakes everyone makes