Regex

Regex Cheatsheet

Quick reference for regular expression syntax including character classes, quantifiers, anchors, groups, and lookaround assertions.

Character Classes

PatternDescription
.Any character except newline
\dDigit [0-9]
\DNon-digit [^0-9]
\wWord character [a-zA-Z0-9_]
\WNon-word character
\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 to z
[a-zA-Z]Any letter
[0-9]Any digit

Anchors

PatternDescription
^Start of string (or line with m flag)
$End of string (or line with m flag)
\bWord boundary
\BNon-word boundary
\AStart of string (absolute)
\ZEnd of string (absolute)

Quantifiers

PatternDescription
*0 or more
+1 or more
?0 or 1
{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)

Groups & References

PatternDescription
(abc)Capturing group
(?:abc)Non-capturing group
(?<name>abc)Named capturing group
\1Backreference to group 1
\k<name>Backreference to named group
(a|b)Alternation: a or b

Lookaround

PatternDescription
(?=abc)Positive lookahead
(?!abc)Negative lookahead
(?<=abc)Positive lookbehind
(?<!abc)Negative lookbehind

Flags

FlagDescription
gGlobal: match all occurrences
iCase-insensitive
mMultiline: ^ and $ match line boundaries
sDotall: . matches newline
uUnicode support
xExtended: allow whitespace and comments

Escape Sequences

PatternDescription
\\Literal backslash
\.Literal dot
\*Literal asterisk
\+, \?, \^, \$Literal special characters
\[, \], \(, \)Literal brackets/parens
\{, \}, |Literal braces/pipe

Common Patterns

# Email (simplified)
[\w.-]+@[\w.-]+\.\w{2,}

# URL
https?://[\w\-.]+(:\d+)?(/\S*)?

# IPv4 address
\b\d{1,3}(\.\d{1,3}){3}\b

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

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

# Hex color
#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})

# HTML tag
<\/?[\w\s="'-]*\/?>

# Whitespace trimming
^\s+|\s+$

# Duplicate words
\b(\w+)\s+\1\b

JavaScript Usage

const re = /pattern/flags;
re.test("string");           // true/false
"string".match(re);          // match array or null
"string".replace(re, "new"); // replaced string
"string".split(re);          // split into array
[..."string".matchAll(re)];  // all matches (with g flag)

Python Usage

import re
re.search(r"pattern", string)    # First match or None
re.match(r"pattern", string)     # Match at start only
re.findall(r"pattern", string)   # List of all matches
re.sub(r"old", "new", string)    # Replace all
re.split(r"pattern", string)     # Split by pattern
re.compile(r"pattern")           # Precompile for reuse