Regular expressions have a reputation for being unreadable because the examples people meet first are deliberately evil (email validation, anyone). Real-world regex is mostly four concepts. This guide covers those, then gives 20 patterns you will reuse constantly — each one testable in a live tester as you read.
The four building blocks
| Concept | Syntax | Meaning |
|---|---|---|
| Anchors | ^ $ | Start / end of the string (or line with m flag) |
| Character classes | \d \w [abc] [^abc] | Digit, word char, set, negated set |
| Quantifiers | * + ? {3,5} | Zero+, one+, optional, bounded repetition |
| Groups | (...) (?:...) | Capture for extraction/replacement; non-capturing to just structure |
Flags worth knowing: g (all matches), i (case-insensitive), m (^ and $ match lines), s (. matches newlines).
The 20 patterns
| Task | Pattern |
|---|---|
| Trim whitespace | ^\s+|\s+$ |
| One or more spaces (collapse) | \s{2,} |
| Integer | ^-?\d+$ |
| Decimal | ^-?\d+\.\d+$ |
| Money amount | \$[\d,]+(\.\d{2})? |
| US phone | \(\d{3}\)\s?\d{3}-\d{4} |
| ISO date | \d{4}-\d{2}-\d{2} |
| Time HH:MM | \b\d{2}:\d{2}\b |
| Email (practical) | [\w.+-]+@[\w-]+\.[\w.]+ |
| URL | https?://[^\s]+ |
| Hex color | #(?:[0-9a-fA-F]{3}){1,2}\b |
| HTML tag | </?[a-zA-Z][^>]*> |
| Quoted string | "[^"]*" |
| Word boundary match | \bword\b |
| First word of line | ^\w+ |
| Extract capture group | key:\s*"?([^",}]+) |
| Remove line comments | ^\s*//.*$ (with m) |
| Split on commas (not in quotes) | ,(?=(?:[^"]*"[^"]*")*[^"]*$) |
| Negative lookahead check | ^(?!.*badword).+$ |
| Replace multiple spaces | \s+ → single space |
The rules that prevent pain
- Anchor when matching whole values — without
^…$,\d{5}matches inside a 17-digit number. - Lazy beats greedy —
.*?stops at the first match of what follows;.*runs to the end. In<title>(.*?)</title>the lazy version is correct. - Test with negative cases — a pattern that matches everything you wanted but also matches what you didn't is worse than no pattern.
- Don't parse HTML with regex — regex is fine for extraction from known, simple markup; it is not a DOM parser.
Practice safely
Paste your text and pattern into the Regex Tester — it shows every match with capture groups and position, so you can see exactly what matched and what didn't before the pattern touches real data. When you are replacing across a document, the same tool previews the replaced output live.
Frequently asked questions
Which dialect should I learn? The patterns above are PCRE-compatible and work with minor tweaks in JavaScript, Python, Go and PHP. Lookarounds ((?=)) don't exist in Go's RE2 — check your engine before relying on them.
Why is my regex slow? Catastrophic backtracking: nested quantifiers like (a+)+ against non-matching input explode exponentially. Rewrite with possessive classes or an explicit loop.