Tools › Cheat sheets › Programming & Tooling › Regular expressions
🧩

Regular expressions cheat sheet

Syntax common to JavaScript, Python, PCRE and most modern engines. Test patterns live in the regex tester. Escape a literal special character with a backslash, for example \. for a dot.

Click any pattern to copy it.

Characters and classes

PatternWhat it does
.Any character except a newline.
\d \w \sA digit, a word character (letter, digit, underscore), a whitespace character.
\D \W \SThe opposites: non-digit, non-word, non-whitespace.
[abc]Any one of a, b or c.
[^abc]Any character except a, b or c.
[a-z0-9]A range: lowercase letters or digits.
a|ba or b.

Anchors and boundaries

PatternWhat it does
^Start of the string (or line with the m flag).
$End of the string (or line with the m flag).
\bA word boundary.
\BNot a word boundary.

Quantifiers

PatternWhat it does
a*Zero or more a.
a+One or more a.
a?Zero or one a (optional).
a{3}Exactly three a.
a{2,5}Between two and five a.
a{2,}Two or more a.
.*?Lazy: as few characters as possible.
a+?Lazy one or more.

Groups and references

PatternWhat it does
(abc)Capture group.
(?:abc)Non-capturing group.
(?<name>abc)Named capture group (JavaScript and PCRE; Python uses (?P<name>abc)).
\1Backreference to the first group.
$1In a replacement string: the first captured group.

Lookarounds

PatternWhat it does
a(?=b)a only if followed by b (positive lookahead).
a(?!b)a only if not followed by b.
(?<=b)aa only if preceded by b (lookbehind).
(?<!b)aa only if not preceded by b.

Flags

PatternWhat it does
iCase-insensitive.
gGlobal: find all matches (JavaScript).
mMultiline: ^ and $ match at each line.
sDot also matches newlines.
uUnicode mode.

Common patterns

PatternWhat it does
^\d+$Digits only.
^[a-z0-9]+(?:-[a-z0-9]+)*$A URL slug such as my-post-title.
^\d{4}-\d{2}-\d{2}$A date in YYYY-MM-DD form (format only, not validity).
^#?[0-9a-fA-F]{6}$A six-digit hex colour.
^[^\s@]+@[^\s@]+\.[^\s@]+$A simple email check. Truly validating email needs a confirmation message.
^(?:\d{1,3}\.){3}\d{1,3}$A loose IPv4 shape (it does not check that each part is 255 or less).
https?://[^\s]+A basic URL finder.
^\s+|\s+$Leading or trailing whitespace (for trimming).
\b(\w+)\s+\1\bA repeated word, such as 'the the'.

Frequently asked questions

What is the difference between greedy and lazy matching?

Greedy quantifiers (*, +) match as much as possible; adding ? makes them lazy and match as little as possible. On <b>a</b><b>b</b>, <.*> matches the whole string while <.*?> matches just the first tag.

Why does my regex fail on newlines?

The dot does not match newlines by default. Use the s flag, or a class such as [\s\S].

More Programming & Tooling cheat sheets

🐍 Python (venv & pip)📗 npmAll Programming & Tooling cheat sheets →
Copied to clipboard