The building blocks
- Literal characters —
catmatches the letters c-a-t in sequence. - Character classes —
[abc]any one of a, b or c;[a-z]a range;[^0-9]anything except a digit. - Shorthands —
\ddigit,\wword character,\swhitespace. Their uppercase forms negate them (\D,\W,\S). - Anchors —
^start of string (or line),$end of string (or line). - Quantifiers —
*zero or more,+one or more,?optional,{2,5}between two and five times. - Groups and alternation —
(abc|def)matches either sequence; numbered groups can be referenced later.
Greedy vs lazy
Quantifiers are greedy by default: <.+> against <a><b> matches the whole string. Adding ? makes it lazy — <.+?> stops at the first > and matches <a>. Most "my regex swallowed too much" problems are fixed by this one character.
Useful starting patterns
digits only ^\d+$
hex colour ^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
IPv4 (loose) ^(?:\d{1,3}\.){3}\d{1,3}$
date YYYY-MM-DD ^\d{4}-\d{2}-\d{2}$
whitespace run \s{2,}
Use the loose IPv4 pattern only for shape validation. It accepts 999.999.999.999; range checking needs code, not regex.
Flags
g— global: find all matches instead of stopping at the firsti— case-insensitivem— multi-line:^and$match at line breakss— dot-all:.also matches newlines
The backtracking trap
Patterns with nested quantifiers such as (a+)+b can take exponential time on input that almost matches. This is catastrophic backtracking and it freezes the browser tab or the server worker. Keep quantifiers from nesting inside other quantifiers, prefer specific character classes over .*, and test with a long non-matching string.
Do not parse HTML with regex
HTML is not a regular language: nested tags, comments and attribute quoting defeat pattern matching. Use a parser. Regex is the right tool for well-defined flat formats — log lines, timestamps, identifiers, simple validation.
What the engine actually does
Most languages use a backtracking engine. The matcher walks the input left to right and tries the pattern at each position until it finds a match. It is not anchored unless you add ^ and $. That has two consequences: a pattern such as cat matches inside “concatenate”, and a check that succeeds has not necessarily validated the whole input. Full-string validation needs both anchors, or containment inside a function that consumes the entire string.
Backtracking also explains the order of preference. A greedy quantifier takes as much as it can, then gives characters back one at a time until the rest of the pattern can match. A lazy quantifier does the opposite: it takes as little as possible and expands until the remainder succeeds. Alternation is tried left to right, so (cat|caterpillar) matches “cat” inside “caterpillar”, while (caterpillar|cat) prefers the longer branch.
Groups, captures and references
(...)— a capturing group; its matched text is available afterwards by index.(?:...)— a non-capturing group; it groups the pattern without storing the result, which keeps numbering predictable and is slightly faster.(?<name>...)— a named group, referenced asgroups.namein JavaScript and by name in Python.\1— a backreference inside the pattern, useful for repeated structures such as matching quotes or duplicated words.
Lookarounds test context without consuming it: (?=...) positive lookahead, (?!...) negative lookahead, and (?<=...) or (?<!...) for the lookbehind forms. They express rules such as “contains a digit somewhere” without moving the match position, but heavy use makes a pattern hard to read and hard to debug.
Mistakes that keep coming back
- Unescaped dots. In
example.comthe dot matches any character, so the pattern also acceptsexampleXcom. Escape it as\.. - Ranges written backwards.
[z-a]is an error or an empty class in most engines; ranges must ascend. - Hyphens in the wrong place. In
[a-z-]the trailing hyphen is literal; in[a-z-0]it forms a range and probably does not mean what you expect. - Reusing a global regex. A
/gpattern keeps itslastIndexbetween calls, so the secondtest()can fail on the same string. Reset it or create a fresh regex each time. - Expecting
.to match newlines. Without thesflag it stops at a line break, which is why multi-line matches fail. - Validating email with one giant pattern. A shape check plus a confirmation message is the only reliable approach; a regex cannot prove that an address exists.
- Assuming
\dmeans any Unicode digit. In JavaScript and many engines it matches ASCII 0–9 only; use Unicode property escapes such as\p{Nd}when you need every script.
Regex versus a real parser
| Task | Regex | Better tool |
|---|---|---|
| Log line extraction | Good fit | Regex with named groups |
| Email shape check | Partial | Regex plus a confirmation email |
| JSON or HTML parsing | Fragile | A dedicated parser |
| Date validation | Shape only | A date library for calendar rules |
| URL parsing | Hard to maintain | The platform URL API |
Building a pattern without losing the afternoon
Start from the smallest pattern that matches one real example, then add cases one at a time. Test both strings that should match and strings that should not, because an overly loose pattern usually passes every positive test. Anchor last: adding ^ and $ at the end is much safer than debugging an over-anchored pattern from the start. Keep the result readable with named groups and non-capturing groups, and put a comment or a test fixture next to it in code, since the next reader will not remember what each bracket was for.
Practical checklist
- Decide up front whether you validate the whole string or search inside it, then add anchors accordingly.
- Escape literal metacharacters, especially
.,+,(and$. - Prefer specific classes such as
[a-z0-9]over.*to limit backtracking. - Test long, nearly matching inputs to catch catastrophic backtracking before production.
- Use a parser for nested formats and keep regex for flat, well-defined text.
- Create a fresh regex per call whenever the
goryflag is in use.
Try patterns against real samples in our Regex Tester, which highlights matches and capture groups as you type. For escaping characters before they reach a regex or a URL, see Base64 and URL encoding.