bitlvl
EN

Regex cheat sheet

The syntax shared by every mainstream engine, with the differences in one table at the end.

Fits on one A4 / Letter page in portrait; use “Save as PDF” in the print dialog to keep a copy.

Anchors and boundaries

^ $start / end of text (of line with m flag)
\A \z \Zstart / end of text regardless of flags (not in JS)
\b \Bword boundary / not

Characters

.any char except newline (any with s flag)
\d \w \sdigit, word char, whitespace; \D \W \S negate
[abc] [a-z] [^abc]set, range, negated set
[\]\\^-]inside a set only ] \ ^ - need escaping
\t \n \r \xHH \uHHHHtab, newline, CR, hex, Unicode
\p{L} \p{Lu} \p{N} \p{Script=Cyrillic}Unicode properties (u flag in JS)
[[:alpha:]] [[:digit:]]POSIX classes (grep, PCRE; not JS)
\. \* \( \\escaped metacharacter = literal

Quantifiers

* + ?0+, 1+, 0 or 1
{n} {n,} {n,m}exactly, at least, between
*? +? ?? {n,m}?lazy: as few as possible
*+ ++ ?+possessive: no backtracking (PCRE, Java)

Groups

(abc)capture, numbered from 1
(?:abc)no capture
(?<name>abc)named (Python: (?P<name>…))
\1 \k<name>backreference (Python: (?P=name))
a|balternation (lowest precedence)
(?>abc)atomic group (PCRE, Java)
(?i)abc (?i:abc)inline flag, scoped inline flag

Lookaround (zero-width)

(?=x)followed by x
(?!x)not followed by x
(?<=x)preceded by x
(?<!x)not preceded by x

Flags

gall matches (JS, PHP via function)
iignore case
m^ $ match at line breaks
s. matches newline (DOTALL)
xignore whitespace and # comments in the pattern (PCRE, Python; not JS)
uUnicode (JS); required for \p{}
ysticky (JS)

Replacement

$1 $<name> $&JS, .NET: group, named, whole match
\1 \g<name>Python re.sub
$1 \1 ${name}PCRE / PHP preg_replace; Go uses $1 and ${name}
sed 's/(a)(b)/\2\1/'sed -E (basic sed needs \( \))

Common patterns

^\s*$blank line
\s+$trailing whitespace
\b(?:\d{1,3}\.){3}\d{1,3}\bIPv4 (loose)
[\w.+-]+@[\w-]+(?:\.[\w-]+)+email (practical)
https?://[^\s"'<>]+URL
\d{4}-\d{2}-\d{2}ISO date
#(?:[0-9a-fA-F]{3}){1,2}\bhex colour
"(?:[^"\\]|\\.)*"double-quoted string with escapes
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$password with digit, lower, upper, 8+
(\w+)\s+\1repeated word

Flavour differences

JavaScriptno \A \z, no x flag, no possessive/atomic; lookbehind yes; named groups (?<n>)
PCRE (PHP, nginx, HAProxy)everything; delimiters /…/ in PHP
Python re(?P<n>), no possessive before 3.11, \Z = end
Go RE2, Rust regexlinear time; no lookaround, no backreferences
grep -E / sed -EERE: no \d (use [0-9]), POSIX classes, no lazy quantifiers
grep (basic)\( \) \{ \} \+ \? escaped to be special
Javapossessive, atomic; strings need double backslashes

Questions

Where can I test a pattern?

The regex tester highlights matches live, lists groups, previews a replacement and explains the pattern token by token.