Regex Course
Regex Cheatsheet
A quick, printable reference for regular expressions: literals, character classes, greedy vs lazy quantifiers, anchors, groups and lookarounds, flags, replace/split, and ReDoS defense. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Core Regex Invariants & Pitfalls to Avoid
Five common traps causing false positives, shared-state bugs, or exponential ReDoS hangs.
- Always wrap full-string validation in ^...$: without anchors /\d+/ accepts "abc123def".
- Escape literal dots (\.) in domains, IPs, and filenames: unescaped . matches any character.
- Never nest repeating quantifiers like (a+)+ or (\w+\s+)+ over arbitrary input — they trigger catastrophic backtracking (ReDoS).
- With global flag /.../g in JavaScript, calling .test() advances lastIndex and alternates between true/false across repeated calls.
- Remember .* and .+ are greedy: reach for .*?, .+?, or negated character classes [^"]+ between delimiters.
1. Basic Syntax
Literal patterns
/hello/ // matches "hello" /Hello/i // case-insensitive /^abc/ // anchored to start of stringSlashes delimit the pattern; without flags matching is case-sensitive.
Pitfall: Omitting ^ or $ matches anywhere inside the text rather than matching the entire input.
Meta-characters
. ^ $ * + ? ( ) [ ] { } | \Characters with special syntax meaning — escape with \ to match literally.
Pitfall: Inside [...], most meta-characters turn literal ([.] matches a dot), while ^, -, ], and \ still carry special rules.
Wildcard .
/a.c/ // a + any single character except newline + c /a.c/s // dotAll flag (s): matches newline \n tooMatches one arbitrary character (excluding \n unless the s flag is active).
Pitfall: In URLs or delimited formats, .* often eats past delimiters: prefer negated classes like [^/]+ or [^,]+.
2. Predefined Classes & Unicode
Character classes
\d digit [0-9] \D non-digit \w word [A-Za-z0-9_] \W non-word \s whitespace \S non-whitespaceUppercase shorthands represent exact negated complements of lowercase ones.
Pitfall: \w matches underscore _ and ASCII letters only in JS — it rejects accented characters and hyphens.
Custom classes
[abc] // one of a, b, c [a-z] // range a..z [A-Za-z0-9_] // equivalent to ASCII \w [^abc] // NEGATED: any character except a, b, c [.,;:] // literal ASCII punctuationEvery character class [...] matches exactly one character from the allowed set.
Pitfall: [1-31] does NOT match integers 1 through 31 — it matches digits 1, 2, or 3!
Unicode (with u flag)
\p{L} // any Unicode Letter \p{N} // any Unicode Number \p{S} // Symbol \p{Script=Latin} // Latin script \P{L} // non-letterHandle accents, multilingual scripts, and emojis safely with flags u or v.
Pitfall: Unicode property escapes \p{...} throw a SyntaxError unless flag /u or /v is present.
3. Quantifiers
Base multiplicity
a* 0 or more a+ 1 or more a? 0 or 1 (optional) a{3} exact 3 a{2,5} from 2 to 5 a{2,} at least 2Applies to the immediately preceding character, class, or parenthesized group.
Pitfall: Never add whitespace inside {2, 5}: many regex engines fall back to matching literal text instead.
Greedy vs Lazy
.+ greedy: consumes as much as possible .+? lazy: consumes as little as possible .*? lazy zero-or-more a{2,5}? lazy bounded repetitionAppend ? immediately after any quantifier to stop at the earliest valid match.
Pitfall: On "<tag>a</tag><tag>b</tag>", /<tag>.*<\/tag>/ matches across both tags at once — use .*? or [^<]*.
4. Anchors & Boundaries
Boundaries
^ // start of string (or line with m flag) $ // end of string (or line with m flag) \b // word boundary between \w and \W \B // non-word boundary // \A and \z are PCRE/Python-style anchors (not supported in JS)Anchors assert zero-width positions without consuming characters.
Pitfall: With multi-line input, remember $ matches line endings only when /m is enabled.
Practical examples
/^abc/ // starts with abc /abc$/ // ends with abc /\bword\b/ // standalone word /^\s*$/m // blank line (multiline flag m)Combine ^, $, and \b to anchor complete strings or whole tokens.
Pitfall: \b relies on ASCII \w definitions, so boundaries around accented letters like \bcafé\b fail cleanly.
5. Groups, Backreferences & Lookaround
Groups & alternatives
(abc) // capturing group ($1) (?:abc) // non-capturing group (?<name>abc) // named group: groups.name / $<name> a|b|c // alternation (a or b or c)Prefer non-capturing (?:...) when grouping for repetition or alternation without polluting $1.
Pitfall: Alternation | spans the whole enclosing context: ^a|b$ matches strings starting with a OR ending with b — write ^(?:a|b)$!
Backreferences
(\w+)\s+\1 // consecutive duplicate word (?<a>\w)\k<a> // named backreference // JS: str.replace(/(\w+) (\w+)/, '$2 $1')Matches the exact substring previously captured by an earlier group.
Pitfall: Backreferences prohibit linear DFA engines (disallowed in RE2 and Rust’s standard regex crate).
Lookahead (zero-width)
(?=...) // positive: must be followed by ... (?!...) // negative: must NOT be followed by ... \d+(?= USD) // digits only when followed by " USD"Asserts trailing context without including those characters in the match.
Pitfall: Unanchored lookarounds inside tight loops can force repeated backtracking probes.
Lookbehind (ES2018+)
(?<=...) // positive: must be preceded by ... (?<!...) // negative: must NOT be preceded by ... (?<=\$)\d+ // digits only when preceded by $Asserts preceding context directly before the current position.
Pitfall: Classic Python/PCRE require fixed-length lookbehind expressions, though JS ES2018+ supports variable length.
6. Flags, Replace & Split
The 8 Flags (dgimsuvy)
// g: global i: ignoreCase m: multiline (^/$) // s: dotAll u: unicode v: unicodeSets // y: sticky d: hasIndices const gi = /token/gi; // all case-insensitive matchesCommon pairs: gi (global case-insensitive), gm (line-based), gu (real Unicode text).
Pitfall: Reusing a /g literal repeatedly with .test() without resetting lastIndex = 0 alternates true/false inconsistently.
replace & callbacks
'foo bar'.replace(/o/g, '0') // 'f00 bar' 'John Doe'.replace(/(\w+) (\w+)/, '$2 $1') date.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1'); str.replace(/(\d{4})-(\d{2})/, (_, year, month) => `${month}/${year}`);Use replacement callbacks for custom transformations on captured pieces.
Pitfall: Calling .replace(/o/, ...) without /g swaps only the first occurrence — pass /g or call replaceAll().
split & replacement tokens
'a, b ,c, d'.split(/\s*,\s*/) // ['a', 'b', 'c', 'd'] // Replace tokens: $1..$9, $<name>, $& (match), $` (before), $' (after), $$ (literal $)Regex splits absorb irregular whitespace cleanly around separators.
Pitfall: Adding a capturing group inside .split(/(,)/) splices the captured delimiter tokens back into the result array!
7. Practical Patterns & Anti-ReDoS
Everyday starter patterns
Email (basic) : /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/ IPv4 (shape) : /\b(?:\d{1,3}\.){3}\d{1,3}\b/ URL http(s) : /https?:\/\/[\w.-]+(?::\d+)?(?:\/[^\s]*)?/ Decimal : /-?\d+(?:\.\d+)?/ Trim : s.replace(/^\s+|\s+$/g, '')Good structural pre-checks; validate numeric ranges (e.g. IP octets <= 255) explicitly in code.
Pitfall: Avoid giant RFC-5322 email regexes — check basic structure and confirm ownership via verification email.
Catastrophic patterns & refactoring
DANGEROUS: (a+)+b | (a|a)* | ^(\w+\s+)+$ SAFE : a+b | a* | ^(?:\w+\s+)*\w+$Flatten nested quantifiers, make alternatives disjoint, and bound maximum input length.
Pitfall: Running ^(\w+\s+)+$ against long malformed strings can freeze a browser tab or Node server for seconds (ReDoS).