Regular expressions

Enough regex to be dangerous — and a few patterns you can paste straight in.

Character classes

.
Any character except newline
\d / \D
Digit / non-digit
\w / \W
Word char [A-Za-z0-9_] / non-word
\s / \S
Whitespace / non-whitespace
[abc] / [^abc]
One of a, b, c / anything but
[a-z0-9]
Ranges

Quantifiers

*
0 or more
+
1 or more
?
0 or 1
{3} / {2,5} / {2,}
Exactly / between / at least
*? +? ??
Lazy (non-greedy) versions

Anchors & boundaries

^ / $
Start / end of string (or line with m flag)
\b / \B
Word boundary / not a boundary
\A / \z
Absolute start / end (where supported)

Groups & alternation

(abc)
Capturing group
(?:abc)
Non-capturing group
(?<year>\d{4})
Named group
a|b
Either a or b
\1 / $1
Backreference in pattern / in replacement

Lookarounds

x(?=y)
x followed by y (lookahead)
x(?!y)
x not followed by y
(?<=y)x
x preceded by y (lookbehind)
(?<!y)x
x not preceded by y

Flags

i
Case-insensitive
g
Global — all matches, not just the first
m
Multiline — ^/$ match per line
s
Dot matches newline too
x
Verbose — ignore whitespace, allow comments
Tip: Greedy quantifiers grab as much as possible. <.+> on <b>hi</b> matches the whole thing; <.+?> stops at the first >.

Useful patterns

# Email (pragmatic, not RFC-perfect)
^[\w.+-]+@[\w-]+\.[\w.-]+$

# ISO date  YYYY-MM-DD
^(?<y>\d{4})-(?<m>0[1-9]|1[0-2])-(?<d>0[1-9]|[12]\d|3[01])$

# IPv4 address
^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$

# Hex colour  #fff or #ffffff
^#(?:[0-9a-fA-F]{3}){1,2}$

# Trim surrounding whitespace (replace with "")
^\s+|\s+$