Regular Expressions: Useful Patterns and Common Pitfalls
Regular expressions are a compact language for describing text patterns. They are brilliant for quick validation, search and extraction, and they are also responsible for a surprising number of bugs and a few outages. This guide covers the patterns you will actually reuse, the details that trip people up, and one failure mode, catastrophic backtracking, that is worth seeing with your own eyes.
Anchors, classes and quantifiers in a minute
Most patterns are built from a few pieces. ^ and $ anchor to the start and end of the input (or of each line with the m flag). \d, \w and \s match a digit, a word character and whitespace. [abc] is a character class, [^abc] its negation, and . matches any character except a newline unless the s flag is on. Quantifiers say how many: ? (0 or 1), * (0 or more), + (1 or more), {3}, {2,5}.
The most common beginner bug is forgetting anchors. \d{4} matches inside abc12345xyz, so it is a search, not a validation. To say "the whole string is exactly four digits" you need ^\d{4}$. In JavaScript, String.prototype.match and RegExp.test both search by default, so validation patterns almost always need both anchors.
Reusable patterns, with honest limits
All of these use JavaScript syntax and were checked against sample inputs. None is a complete validator; each says what it catches and what it misses.
| Purpose | Pattern | Limit |
|---|---|---|
| ISO date | ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$ | Accepts 2026-02-31. Regex checks shape; use a date parser for real validity. |
| Hex colour | ^#(?:[0-9a-f]{3}|[0-9a-f]{6})$ with i | Does not cover 4- or 8-digit forms with alpha. |
| Semantic version | ^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$ | Core versions only; pre-release and build suffixes need more. |
| UUID (any version) | ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ with i | Checks layout only, not version or variant bits. See UUID versions explained. |
| Email sanity check | ^[^\s@]+@[^\s@]+\.[^\s@]+$ | Only catches typos like a missing @. |
About email: no regex can fully validate an address. The real grammar (RFC 5322) allows quoted local parts, comments and internationalised domains, and a perfectly formed address can still bounce because the mailbox does not exist. The sensible approach is a loose shape check like the one above, then send a confirmation message. Anything stricter will eventually reject a real customer.
Greedy versus lazy
Quantifiers are greedy by default: they take as much as they can and give back only if the rest of the pattern fails. Add ? after a quantifier to make it lazy. The classic demonstration is HTML-like text:
const s = "<b>x</b><b>y</b>";
s.match(/<b>.*<\/b>/)[0]; // "<b>x</b><b>y</b>" greedy: runs to the last closing tag
s.match(/<b>.*?<\/b>/)[0]; // "<b>x</b>" lazy: stops at the first
A negated class is often better than a lazy dot: <b>[^<]*</b> says exactly what you mean and is cheaper to evaluate. And for genuinely nested markup, use a parser rather than a regex.
Groups, named groups and lookahead
Parentheses create a capturing group; (?:...) groups without capturing. Numbered groups become fragile as patterns grow, so prefer named groups, which JavaScript supports as (?<name>...):
const m = "2026-11-18".match(/^(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})$/);
m.groups.y; // "2026"
Lookahead asserts something follows without consuming it. \d+(?= USD) matches 100 in price: 100 USD but leaves the currency out of the match; (?!...) is the negative form. Lookbehind ((?<=...)) works in modern JavaScript engines too, but older Safari versions did not support it, so check your target browsers.
Flags and escaping
The flags you will meet are g (find all matches), i (case-insensitive), m (anchors match at line boundaries), s (dot matches newline), u (Unicode-aware) and y (sticky). Without g, matching stops at the first hit.
The characters . * + ? ^ $ { } ( ) | [ ] \ are special, so a literal dot is \.. A second layer of escaping appears when the pattern lives in a string: new RegExp("\\d+") needs a doubled backslash because the string literal consumes one. Regex literals (/\d+/) avoid that. If you build a pattern from user input, escape it first or someone will inject metacharacters. The String Escape tool helps when you are juggling these layers.
Catastrophic backtracking
Most JavaScript engines match with backtracking: when a path fails, they return to earlier choice points and try alternatives. With ambiguous nested quantifiers, the number of paths grows exponentially. The textbook example is ^(a+)+$. Against a string of a characters followed by one b, the engine cannot match the final $, so it tries every way of splitting the run of a characters among the inner and outer plus.
I ran this in Node on a laptop, timing /^(a+)+$/.test("a".repeat(n) + "b"):
n = 20 about 20-40 ms
n = 24 about 80 ms
n = 26 0.3 s in one run, 2.7 s in another
n = 28 1.3 s
n = 30 5.4 s
Timings are noisy, but the trend is the point: roughly each extra two characters multiplies the time. A 5,000-character string of only a characters against the harmless ^a+$ took under a millisecond. In a server, one user-supplied string against a vulnerable pattern can pin a CPU core. This is the ReDoS class of bug.
How to avoid it
- Remove the ambiguity.
^(a+)+$means the same as^a+$. Rewrite so that every character can be matched in only one way. - Limit the input. Reject strings above a sensible length before matching, and use bounded quantifiers like
{1,64}. - Anchor and be specific. Prefer
[^"]*to.*inside delimiters. - Know the engine. Possessive quantifiers and atomic groups, which forbid giving characters back, exist in some flavours (PCRE, Java) but not in JavaScript. Linear-time engines such as RE2 (used by Go and available as a library elsewhere) avoid the problem by not supporting backreferences and backtracking at all.
- Test with hostile input, not only valid samples.
Testing patterns safely
Build and debug patterns on real sample text before shipping them. Our Regex Tester runs your pattern with the browser's own JavaScript RegExp engine: you type the pattern and flags (default gi), paste text, and it lists each match with its index and numbered capture groups. Because it is JavaScript, lookbehind and named groups work if your browser supports them, but PCRE-only features such as possessive quantifiers or recursion will produce an invalid-pattern error. A very slow pattern can freeze the tab, so test suspicious ones with short inputs first. When a refactored pattern behaves differently from the old one, the Text Diff Checker can compare the match output of the two. Also see Common JSON Syntax Errors for another case where reaching for a parser beats pattern matching.