Regular Expressions Cheatsheet

Pattern syntax, common patterns, and quick examples

Character Classes
.Any character except newline
\dDigit [0-9]
\DNon-digit [^0-9]
\wWord char [a-zA-Z0-9_]
\WNon-word char
\sWhitespace [ \t\n\r\f\v]
\SNon-whitespace
[abc]Any of a, b, or c
[^abc]Not a, b, or c
[a-z]Range: a through z
[a-zA-Z0-9]Alphanumeric
Quantifiers
*0 or more (greedy)
+1 or more (greedy)
?0 or 1 (optional)
{3}Exactly 3
{3,}3 or more
{3,5}Between 3 and 5
*?0 or more (lazy)
+?1 or more (lazy)
??0 or 1 (lazy)
Greedy vs Lazy
Input: <b>bold</b>text<b>more</b> <.+> matches: <b>bold</b>text<b>more</b> <.+?> matches: <b>bold</b>text<b>more</b>
Anchors & Boundaries
^Start of string (or line with m flag)
$End of string (or line with m flag)
\bWord boundary
\BNon-word boundary
\AStart of string (always)
\ZEnd of string (always)
Word boundary example
\bcat\b in "concatenate a cat" matches: concatenate a cat
Groups & Alternation
(abc)Capture group
(?:abc)Non-capturing group
(?<name>abc)Named capture group
\1Backreference to group 1
\k<name>Backreference by name
a|bAlternation: a or b
(a|b)cac or bc
Backreference example
(\w+)\s+\1 in "the the quick" matches: the the quick
Lookahead & Lookbehind
(?=abc)Positive lookahead
(?!abc)Negative lookahead
(?<=abc)Positive lookbehind
(?<!abc)Negative lookbehind
Examples
\d+(?= dollars) in "100 dollars" matches: 100 dollars (?<=\$)\d+ in "price $50" matches: price $50 \b\w+(?!ing\b) in "running fast" matches: running fast
Special / Escaped Characters
\nNewline
\tTab
\rCarriage return
\\Literal backslash
\.Literal dot
\* \+ \?Literal *, +, ?
\( \)Literal parentheses
\[ \]Literal brackets
\{ \}Literal braces
Flags / Modifiers
gGlobal -- all matches, not just first
iCase-insensitive
mMultiline -- ^ and $ match line boundaries
sDotall -- . matches newline too
uUnicode support
xExtended -- ignore whitespace, allow comments
Usage (JavaScript)
/pattern/gi new RegExp('pattern', 'gi')
POSIX Classes (in [ ])
[:alpha:]Letters [a-zA-Z]
[:digit:]Digits [0-9]
[:alnum:]Alphanumeric
[:space:]Whitespace
[:upper:]Uppercase [A-Z]
[:lower:]Lowercase [a-z]
[:punct:]Punctuation
Replacement Patterns
$0 or $&Entire match
$1, $2 ...Capture group 1, 2 ...
${name}Named group
$`Before match
$'After match
Example
Search: (\w+), (\w+) Replace: $2 $1 "Doe, John" => "John Doe"
Common Patterns
Email (simplified)
[\w.+-]+@[\w-]+\.[\w.]+

URL
https?:\/\/[\w\-._~:/?#\[\]@!$&'()*+,;=%]+

IPv4 Address
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b

Phone (US)
\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}

Date (YYYY-MM-DD)
\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])

Time (HH:MM, 24h)
([01]\d|2[0-3]):[0-5]\d

Hex Color
#([0-9a-fA-F]{3}){1,2}\b

HTML Tag
<([a-z]+)([^<]*?)(?:>(.*?)<\/\1>|\s*\/>)

Slug (URL-safe)
^[a-z0-9]+(?:-[a-z0-9]+)*$

Strong Password
(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}

Username (3-16 chars)
^[a-zA-Z0-9_-]{3,16}$

Credit Card (basic)
\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b
ZeroKit.dev — Developer Cheatsheet Bundle