Regex Cheat Sheet

Every piece of regular expression syntax you’re likely to need, with an example you can open in the tester in one click.

Character classes

SyntaxMeaningExampleTry
.Any character except newline/c.t/gTry
\dDigit 0–9/\d+/gTry
\DNot a digit/\D+/gTry
\wWord character [A-Za-z0-9_]/\w+/gTry
\WNot a word character/\W/gTry
\sWhitespace/\s+/gTry
\SNot whitespace/\S+/gTry
[abc]Any one of a, b or c/gr[ae]y/gTry
[^abc]Any character except a, b, c/[^aeiou\s]/gTry
[a-z]A range/[A-F0-9]+/gTry
\p{L}Any Unicode letter (u flag) JS/\p{L}+/guTry

Anchors & boundaries

SyntaxMeaningExampleTry
^Start of string / line (m)/^\w+/gmTry
$End of string / line (m)/\w+$/gmTry
\bWord boundary/\bcat\b/gTry
\BNot a word boundary/\Bcat/gTry

Quantifiers

SyntaxMeaningExampleTry
*0 or more/ab*c/gTry
+1 or more/ab+c/gTry
?0 or 1 (optional)/colou?r/gTry
{3}Exactly 3/\d{3}/gTry
{2,}2 or more/\d{2,}/gTry
{2,4}Between 2 and 4/\d{2,4}/gTry
*? +?Lazy: as few as possible/<.+?>/gTry

Groups & references

SyntaxMeaningExampleTry
(abc)Capture group/(\d{4})-(\d{2})/gTry
(?:abc)Group without capturing/(?:ha)+/gTry
(?<name>…)Named capture group/(?<year>\d{4})-(?<month>\d{2})/gTry
\1Back-reference to group 1/\b(\w+) \1\b/gTry
a|bAlternation (or)/cat|dog/gTry

Lookaround

SyntaxMeaningExampleTry
(?=…)Followed by/\d+(?=px)/gTry
(?!…)Not followed by/\d+(?!px|\d)/gTry
(?<=…)Preceded by/(?<=\$)\d+/gTry
(?<!…)Not preceded by/(?<!\$)\b\d+/gTry

Flags

SyntaxMeaningExampleTry
gGlobal: find all matches/o/gTry
iCase-insensitive/json/giTry
mMultiline: ^ $ match per line/^-/gmTry
sDot matches newline/a.b/gsTry
uUnicode mode/./guTry
ySticky: match at lastIndex only JS/\d/gyTry

Common patterns

Pattern forRegexTry
Email (practical)
Good enough for form checks; the full RFC 5322 grammar is not a sensible regex
^[^\s@]+@[^\s@]+\.[^\s@]{2,}$Try
URL (http/https)
Links in text
https?:\/\/[^\s/$.?#].[^\s]*Try
IPv4 address
Four octets 0–255
\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\bTry
ISO date
YYYY-MM-DD
\b\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\bTry
Hex colour
#rgb or #rrggbb
#(?:[0-9a-fA-F]{3}){1,2}\bTry
UUID
8-4-4-4-12 hex
\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\bTry
Trailing whitespace
Spaces at line ends
[ \t]+$Try
Duplicate words
the the
\b(\w+)\s+\1\bTry
Semantic version
major.minor.patch
\bv?\d+\.\d+\.\d+(?:-[\w.]+)?\bTry

Questions

Does this apply to Python, PHP and Java too?

Nearly all of it. The table is written for JavaScript; rows marked “JS” behave differently or are missing in some other engines. Python uses (?P<name>…) for named groups, for example.

What is the difference between greedy and lazy?

Greedy quantifiers (*, +) take as much as they can and back off; lazy ones (*?, +?) take as little as possible. On <b>x</b>, <.+> matches the whole string while <.+?> matches just <b>.

Related tools