// REF. 03 / PATTERNS
Regex cheat sheet
The regular expression syntax you’ll actually use: characters and classes, anchors, quantifiers, groups, lookarounds and flags, plus the patterns everyone rewrites from scratch every month. It works in JavaScript, Python, Go, Java, PCRE and most editors, with small differences in lookbehind and named-group support.
Two habits pay off fast: anchor your patterns with ^ and $ when you mean the whole string, and reach for a lazy *? before a greedy .* eats more than you wanted.
↓ Download the printable PDF free · letter size · no email needed
Characters
.- any char except newline
\d / \D- digit / not a digit
\w / \W- word char / not
\s / \S- whitespace / not
\.- a literal dot
\t / \n- tab / newline
Classes
[abc]- a, b or c
[^abc]- anything but a, b, c
[a-z]- a range
[A-Za-z0-9_]- same as \w
[\s\S]- truly anything
Anchors
^ / $- start / end of line
\b- word boundary
\B- not a boundary
\A / \z- start / end of string
Quantifiers
*- 0 or more
+- 1 or more
?- 0 or 1
{3}- exactly 3
{2,5}- 2 to 5
{2,}- 2 or more
*? / +?- lazy: as few as possible
Groups
(abc)- capture group
(?:abc)- group, no capture
(?<id>abc)- named group
\1- backreference
a|b- a or b
Lookaround
(?=x)- followed by x
(?!x)- not followed by x
(?<=x)- preceded by x
(?<!x)- not preceded by x
Flags
i- ignore case
g- global, every match
m- ^ and $ per line
s- dot matches newline
x- ignore whitespace
Common
^\s*$- blank line
\d{4}-\d{2}-\d{2}- ISO date
#?[0-9a-f]{6}- hex colour (add i)
\b\w+@\w+\.\w+\b- an email, roughly
^\s+|\s+$- trim whitespace
Here be dragons
.*- greedy. eats the whole line
(a+)+- catastrophic backtracking
<.*>- parsing HTML. please don't
^.*$- matches everything. good luck.
// KEEP IT UNDER YOUR KEYBOARD
Regex Field Manual Desk Mat
from $34 · printed to order in the USA