Regex Cheat Sheet

Quick reference for regular expression syntax and common patterns.

Character Classes

. Any character except newline
\w Word character [a-zA-Z0-9_]
\W Non-word character
\d Digit [0-9]
\D Non-digit
\s Whitespace
\S Non-whitespace
[abc] Any of a, b, or c
[^abc] Not a, b, or c
[a-z] Character range a-z

Anchors

^ Start of string/line
$ End of string/line
\b Word boundary
\B Non-word boundary

Quantifiers

* 0 or more
+ 1 or more
? 0 or 1
{n} Exactly n times
{n,} n or more times
{n,m} Between n and m times
*? 0 or more (lazy)
+? 1 or more (lazy)

Groups & Lookaround

(abc) Capturing group
(?:abc) Non-capturing group
(?<name>abc) Named capturing group
\1 Backreference to group 1
(?=abc) Positive lookahead
(?!abc) Negative lookahead
(?<=abc) Positive lookbehind
(?<!abc) Negative lookbehind
a|b Match a or b

Flags

g Global (all matches)
i Case insensitive
m Multiline (^ and $ match line boundaries)
s Dotall (. matches newline)
u Unicode

Common Patterns

Email
^[\w.-]+@[\w.-]+\.\w{2,}$
URL
https?:\/\/[\w.-]+(?:\/[\w./?%&=-]*)?
Phone (US)
^\(?[\d]{3}\)?[-.\s]?[\d]{3}[-.\s]?[\d]{4}$
IP Address (IPv4)
^(?:\d{1,3}\.){3}\d{1,3}$
Hex Color
^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
Date (YYYY-MM-DD)
^\d{4}-\d{2}-\d{2}$
Password (8+ chars, upper, lower, number)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$

Escape Special Characters

These characters need to be escaped with a backslash:

. * + ? ^ $ { } [ ] \ | ( )