elefcode
← All cheat sheets

Languages

Regex Cheat Sheet — Regular Expression Syntax Reference

Regular expressions are built from a small set of pieces. This reference covers the syntax you actually use day to day, with a short example for each.

Put it into practice with the matching tool.

Test a regex

Advertisement

Character classes

.Any character except newline
[abc]Any one of a, b, or c
[^abc]Any character except a, b, or c
[a-z]Any character in the range a to z
\dAny digit (same as [0-9])
\DAny non-digit
\wWord character: letter, digit, or underscore
\WAny non-word character
\sAny whitespace (space, tab, newline)
\SAny non-whitespace character

Anchors & boundaries

^Start of string (or line with the m flag)
$End of string (or line with the m flag)
\bWord boundary
\BNot a word boundary

Quantifiers

*Zero or more
+One or more
?Zero or one (optional)
{3}Exactly three times
{2,}Two or more times
{2,5}Between two and five times
*?Lazy (non-greedy) — match as little as possible

Groups & alternation

(abc)Capturing group
(?:abc)Non-capturing group
(?<name>abc)Named capturing group
a|bMatch a or b
\1Backreference to the first captured group

Lookaround

(?=abc)Positive lookahead — followed by abc
(?!abc)Negative lookahead — not followed by abc
(?<=abc)Positive lookbehind — preceded by abc
(?<!abc)Negative lookbehind — not preceded by abc

Flags

gGlobal — find all matches, not just the first
iCase-insensitive
mMultiline — ^ and $ match line starts/ends
sDotall — . also matches newline
uUnicode mode

Common patterns

^\S+@\S+\.\S+$Simple email shape
^https?:\/\/Starts with http:// or https://
^\d{4}-\d{2}-\d{2}$ISO date (YYYY-MM-DD)
\b\d{1,3}(\.\d{1,3}){3}\bIPv4 address shape
^[a-z0-9-]+$URL slug (lowercase, digits, hyphens)

More cheat sheets