Regular Expressions Cheat Sheet

A one-page regex reference: anchors, character classes, quantifiers, groups, lookarounds and flags, with an example for each. Syntax follows PCRE, which PHP, JavaScript and most editors share for everything below.

Anchors

TokenMatchesExample
^Start of string (or line with m)^Hello
$End of string (or line with m)world$
\bWord boundary\bcat\b matches “cat”, not “concat”
\BNot a word boundary\Bcat matches “concat”

Character classes

TokenMatchesExample
.Any character except newlinea.c matches “abc”
\d / \DDigit / not a digit\d{4} matches “2026”
\w / \WWord character [A-Za-z0-9_] / not\w+
\s / \SWhitespace / not\s+
[abc]One of a, b, cgr[ae]y
[^abc]Anything but a, b, c[^0-9]
[a-z]A range[A-Fa-f0-9]

Quantifiers

TokenMatchesExample
*0 or moreab*
+1 or more\d+
?0 or 1colou?r
{n} / {n,} / {n,m}Exactly n / n or more / n to m\d{2,4}
*?, +?, ??Lazy versions: match as little as possible<.+?>

Groups and lookarounds

TokenMatchesExample
(abc)Capturing group(\d+)-(\d+)
(?:abc)Group without capturing(?:https?://)?
(?<name>abc)Named group(?<year>\d{4})
a|ba or bcat|dog
\1Back-reference to group 1(\w)\1 matches “ll”
(?=abc) / (?!abc)Followed / not followed by\d+(?= px)
(?<=abc) / (?<!abc)Preceded / not preceded by(?<=\$)\d+

Flags

FlagEffect
iCase-insensitive
gAll matches, not just the first (JavaScript)
m^ and $ match at line breaks
s. also matches newline
uUnicode mode
xIgnore whitespace in the pattern (PCRE)
Regular expressions cheat sheet, one-page PNG

Source from: addedbytes.com