regex.md

Regex #

Regular expressions match patterns in text. The syntax below is the common (PCRE / JavaScript) flavor; most engines agree on the core, with small differences noted.

Character classes #

PatternMatches
.Any character except newline
\d \DDigit / non-digit
\w \WWord char [A-Za-z0-9_] / non-word
\s \SWhitespace / non-whitespace
[abc]Any one of a, b, c
[^abc]Any char except a, b, c
[a-z0-9]Range: lowercase letter or digit

Anchors & boundaries #

PatternMatches
^Start of string (or line with m flag)
$End of string (or line with m flag)
\b \BWord boundary / not a word boundary
\A \zStart / end of string (some engines)

Quantifiers #

PatternMatches
*0 or more
+1 or more
?0 or 1 (optional)
{3}Exactly 3
{2,5}Between 2 and 5
{2,}2 or more
*? +? ??Lazy: match as few as possible

Groups & alternation #

PatternMeaning
(abc)Capturing group (back-referenced as \1)
(?:abc)Non-capturing group
(?<year>\d{4})Named group (\k<year> to back-reference)
a\bAlternation: a or b
\1Back-reference to group 1

Lookarounds #

PatternMatches
(?=foo)Lookahead: followed by foo
(?!foo)Negative lookahead: not followed by foo
(?<=foo)Lookbehind: preceded by foo
(?<!foo)Negative lookbehind: not preceded by foo

Flags #

FlagEffect
gGlobal: all matches, not just the first
iCase-insensitive
mMultiline: ^ and $ match per line
sDotall: . also matches newline
uUnicode mode
xExtended: ignore whitespace / allow comments

Common patterns #

^\d{4}-\d{2}-\d{2}$            ISO date: 2026-06-30
^[\w.+-]+@[\w-]+\.[\w.-]+$     basic email
^https?://[^\s]+$              http or https URL
^#?[0-9a-fA-F]{6}$             hex color
^\+?[\d ()-]{7,}$              loose phone number
(\d)\1                         a repeated digit (back-reference)
\b\w+\b                        each word

Substitution examples #

# sed: capture groups are \1, \2 in the replacement
echo "2026-06-30" | sed -E 's/(\d{4})-(\d{2})-(\d{2})/\3\/\2\/\1/'

# JavaScript: $1 in the replacement, named groups too
"2026-06-30".replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, "$<d>/$<m>/$<y>")

# Python: r"" raw strings avoid double-escaping backslashes
import re
re.sub(r"(\w+)@(\w+)", r"\2:\1", "user@host")

© 2026 anguishedturtle.comBit Night RunnerSupportPrivacy