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 #
| Pattern | Matches |
. | Any character except newline |
\d \D | Digit / non-digit |
\w \W | Word char [A-Za-z0-9_] / non-word |
\s \S | Whitespace / 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 #
| Pattern | Matches |
^ | Start of string (or line with m flag) |
$ | End of string (or line with m flag) |
\b \B | Word boundary / not a word boundary |
\A \z | Start / end of string (some engines) |
Quantifiers #
| Pattern | Matches |
* | 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 #
| Pattern | Meaning |
(abc) | Capturing group (back-referenced as \1) |
(?:abc) | Non-capturing group |
(?<year>\d{4}) | Named group (\k<year> to back-reference) |
a\ | b | Alternation: a or b |
\1 | Back-reference to group 1 |
Lookarounds #
| Pattern | Matches |
(?=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 #
| Flag | Effect |
g | Global: all matches, not just the first |
i | Case-insensitive |
m | Multiline: ^ and $ match per line |
s | Dotall: . also matches newline |
u | Unicode mode |
x | Extended: 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")