Most regular expressions in production are not clever. They are small patterns for trimming whitespace, validating a format loosely, or extracting one field from a log line. The clever ones tend to be the ones that break.
This guide covers the syntax you actually use, five patterns worth keeping, the difference between greedy and lazy matching, and how to avoid a regex that freezes a server.
The syntax refresher
| Token | Meaning |
|---|---|
. | Any character except a newline |
\d \w \s | Digit, word character, whitespace |
^ $ | Start and end of the string (or line, with the m flag) |
* + ? | Zero or more, one or more, optional |
{2,5} | Between two and five repetitions |
[abc] [^abc] | One of these characters, or none of them |
(...) | Capture group |
(?:...) | Non-capturing group |
| | Alternation: this or that |
Four flags do most of the work:
imakes matching case-insensitive.gfinds every match instead of the first one.mmakes^and$match line boundaries.slets.match newlines.
Five patterns worth keeping
1. Trim surrounding whitespace
^\s+|\s+$
Replace each match with an empty string. It is clearer than a hand-written loop and works across tabs, non-breaking spaces and line breaks.
2. A pragmatic email check
^[^\s@]+@[^\s@]+\.[^\s@]{2,}$
This does not implement RFC 5322, and it should not try. It rejects strings with no @, no dot, or spaces, which catches typos without rejecting valid addresses. The only reliable email validation is sending a message and waiting for a reply.
3. An HTTP or HTTPS URL
^https?://[^\s/$.?#].[^\s]*$
Useful for filtering links in text. It intentionally accepts more than a strict URI parser; the goal is to find candidates, not to prove validity.
4. An ISO date
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
This checks the shape and the obvious ranges. It still accepts 2026-02-31, because month lengths and leap years are calendar logic, not pattern logic. Validate the date itself after the format check.
5. Collapse duplicate blank lines
\n{3,}
Replace with two newlines to keep paragraph spacing while removing accidental gaps.
Greedy vs lazy
Quantifiers are greedy by default: .* takes as much as it can, then backtracks until the rest of the pattern fits. Adding ? makes it lazy, so it takes as little as possible.
Input: <b>one</b> <b>two</b>
/<b>.*<\/b>/ matches "<b>one</b> <b>two</b>"
/<b>.*?<\/b>/ matches "<b>one</b>"
Greedy matching is usually what you want when the pattern has a unique end anchor. Lazy matching is better when you are extracting repeated delimited sections.
Groups and lookarounds
Capture groups let you pull out parts of a match:
^(\d{4})-(\d{2})-(\d{2})$
Lookarounds assert context without consuming it:
(?=...)— must be followed by this.(?!...)— must not be followed by this.(?<=...)— must be preceded by this.(?<!...)— must not be preceded by this.
A common use is a password rule that requires a digit without including it in the match:
^(?=.*\d)(?=.*[a-z]).{8,}$
Lookarounds are powerful and easy to overuse. If a pattern needs more than two, a small parsing function is usually easier to read and debug.
Catastrophic backtracking
Nested quantifiers can turn a small input into an enormous search space:
^(a+)+$
For a string of as followed by !, the engine tries every way to split the as between the two quantifiers before failing. Twenty characters can take seconds; thirty can take minutes. The same problem appears with (.*)*, (\w+\s?)* and similar shapes.
How to avoid it:
- Avoid nested quantifiers over the same character class.
- Prefer explicit limits:
{1,64}instead of+. - Anchor patterns and keep them specific.
- Test with a long non-matching input, not only a matching one.
- Use a regex engine with a linear-time guarantee if input is untrusted.
A pattern that is correct but slow is still a denial-of-service risk when it runs on user input.
How to test a pattern
Testing is not just “does it match the sample”. Check three things:
- What it matches — including unexpected extra text.
- What it does not match — near-miss inputs that should fail.
- How it behaves on long input — a 10,000-character line should return quickly.
The Regex Tester runs patterns in your browser, highlights every match and shows capture groups, so you can iterate without writing a scratch script. For cleaning a list of lines before matching, the Line Tools can deduplicate, sort and trim first. And if you are measuring how much text a pattern removed, the Word Counter gives you the before and after numbers.
A practical checklist
- Start with the smallest pattern that solves the case.
- Anchor with
^and$when validating a whole string. - Use non-capturing groups unless you need the capture.
- Test matching and non-matching inputs.
- Cap repetition for untrusted input.
- Put the pattern in one place, with a comment and a test, instead of copying it across files.
Regular expressions are a sharp tool. The useful ones are short, anchored and tested against real data — and the fastest way to keep them that way is to try them in a tester before they reach production.