regex· 7 min read

Regular expressions, demystified

The building blocks of regex in one page. Everything here works in JavaScript and Python; paste any pattern into the regex tester to see it in action.

Character classes

TokenMatches
.Any character except a newline (add the s flag to include it)
\d / \DA digit / anything but a digit
\w / \WA word character [A-Za-z0-9_] / anything else
\s / \SWhitespace (space, tab, newline) / non-whitespace
[abc]One of a, b or c
[^abc]Any character except those
[a-z0-9]A range of characters
\., \(, \\A literal special character

Quantifiers

QuantifierMeans
*0 or more
+1 or more
?0 or 1 (optional)
{3}Exactly 3
{2,5} / {2,}Between 2 and 5 / at least 2
*?, +?, {2,5}?Lazy versions — match as little as possible
text:    <b>bold</b>
<.+>     # greedy: matches the whole string
<.+?>    # lazy:   matches "<b>" and then "</b>"

Anchors and boundaries

  • ^ and $ — start and end of the string, or of each line with the m flag.
  • \b — a word boundary: \bcat\b matches “cat” but not “concatenate”.
  • \B — not a word boundary.

Anchors match positions, not characters. That is why ^$ with the m flag finds empty lines without consuming anything.

Groups and backreferences

SyntaxWhat it does
(abc)Capturing group, available as $1 / \1
(?:abc)Group without capturing
(?<year>\d{4})Named group (Python also accepts (?P<year>…))
cat|dogAlternation: either side
\b(\w+)\s+\1\bBackreference: finds doubled words like “the the”
// JavaScript
const m = "2026-11-27".match(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/);
m.groups.y;                                            // "2026"
"2026-11-27".replace(/(\d+)-(\d+)-(\d+)/, "$3.$2.$1"); // "27.11.2026"
# Python
import re
re.sub(r"(\d+)-(\d+)-(\d+)", r"\3.\2.\1", "2026-11-27")   # '27.11.2026'
re.findall(r"#[0-9a-fA-F]{6}\b", css)                      # all hex colours

Lookarounds

Lookarounds check what is next to the current position without including it in the match.

SyntaxNameExample
(?=…)Lookahead\d+(?=px) — numbers followed by “px”
(?!…)Negative lookahead\bfoo(?!bar) — “foo” not followed by “bar”
(?<=…)Lookbehind(?<=\$)\d+ — amount after a dollar sign
(?<!…)Negative lookbehind(?<!-)\b\d+ — numbers without a minus
# at least 8 chars, one digit and one lowercase letter
^(?=.*\d)(?=.*[a-z]).{8,}$

Handy recipes

TaskPattern
ISO date\b\d{4}-\d{2}-\d{2}\b
Hex colour#(?:[0-9a-fA-F]{3}){1,2}\b
Trailing whitespace (flag m)[ \t]+$
Blank lines (flag m)^\s*$
Doubled words (flag i)\b(\w+)\s+\1\b
Semantic version\bv?\d+\.\d+\.\d+\b
Key = value line^(\w+)\s*=\s*(.*)$

Keep patterns for validation loose and readable. For things like email addresses, a simple sanity check plus a confirmation step beats a 400-character expression.