tomai
Log in

Regex Handbook: Patterns You Will Actually Reuse

Regular expressions pack a whole search language into a single line, which is why they feel cryptic until the pieces click. This handbook covers the 20 percent of syntax that solves 80 percent of jobs: finding emails in pasted text, validating input, splitting logs and rewriting filenames in bulk.

1. Literals, dots and character classes

Most characters match themselves; the dot matches any character except a newline. Square brackets define a set — [0-9] takes any digit, [^0-9] takes anything but a digit — while shorthands like \d, \w and \s cover digits, word characters and whitespace. Prefer an explicit class over a bare dot whenever you know what belongs there.

2. Anchors and quantifiers

^ pins to the start and $ to the end, so ^hi only matches strings that begin with hi. Add + for one-or-more, * for zero-or-more and ? for optional; a trailing ? after any of them switches to lazy matching, which stops at the first opportunity instead of the last. Greedy versus lazy is the single most common source of surprising matches.

3. Groups, alternation and lookarounds

Parentheses group and capture — (cat|dog)s? matches cat, cats, dog or dogs — while (?:…) groups without capturing. Lookaheads like \d+(?=px) check what follows without consuming it, so you can require a suffix and leave it in place for the next match. Named groups document intent for whoever reads the pattern next.

4. Flags change everything

Letters after the closing slash tune the engine: g finds all matches instead of the first, i ignores case, m makes anchors work per line, s lets the dot cross newlines, u enables full Unicode and y sticks matching to one position. The wrong flag set is a frequent reason a correct-looking pattern returns nothing.

5. The backtracking trap

Nested quantifiers such as (a+)+ on a long non-matching string can send the engine down an exponential number of paths and freeze the tab. Keep repetitions flat, prefer possessive-style rewrites or atomic groups where supported, and test suspicious patterns against hostile input before shipping — paste them into our regex tester, which highlights every match and group live in your browser.