Regular Expressions Explained: Patterns, Groups & Real Examples

Regex looks like keyboard noise — \d{3}-\d{4} — but it is a tiny language for describing text. Learn the building blocks, how the engine actually matches, and the patterns worth memorising.

📂 Developer Essentials ⏱ About 14 minutes 📶 Intermediate 🛠️ Pairs with: Regex Tester

What you will learn

  • Read a regex out loud and say what it matches
  • Use character classes, quantifiers, anchors and groups with confidence
  • Know when greedy matching bites — and how lazy matching fixes it
  • Write patterns for emails, dates, phone numbers and log lines
  • Recognise the patterns that freeze a program (catastrophic backtracking)
In this guide
  1. What a regular expression is
  2. The building blocks
  3. How the engine actually matches: greedy, lazy and backtracking
  4. Patterns worth memorising
  5. Flags: the switches that change everything
  6. Common mistakes
  7. Try it: Regex Tester
  8. Frequently asked questions

What a regular expression is

A regular expression (regex) is a pattern that describes a set of strings. Instead of writing code that says “check each character one by one”, you write a compact description — \d{3}-\d{4} — and ask: does this text contain something shaped like that?

Regexes live everywhere: searching in an editor, validating a form, renaming a thousand files, parsing a log, highlighting matches in a page. They are not a programming language of their own, but almost every language embeds the same core syntax — learn it once and it follows you from JavaScript to Python to the command line.

The catch is readability. Regex is famously write-only: a pattern you wrote last month can look like line noise today. The fix is not to avoid regex, but to build patterns from small named pieces and to test them — which is exactly what this guide and the paired tester are for.

The building blocks

Nearly every pattern is assembled from these pieces:

PieceMeaningExample
abcLiteral charactersmatches abc exactly
.Any single character (except newline)a.c matches abc, a-c
\d \w \sDigit, word character, whitespace\d matches 7
\D \W \SThe opposites (not a digit, etc.)\D matches a
[abc] [a-z] [^0-9]Character class / negated class[aeiou] matches one vowel
* + ? {n} {n,m}Quantifiers: 0+, 1+, 0/1, exactly n, n to m\d{3} matches three digits
^ $ \bAnchors: start, end, word boundary^cat matches only at the start
( ) (?: ) (?<name> )Capturing group, non-capturing, named group(\d+)-(\d+) captures two numbers
|Alternation (or)cat|dog matches either
\Escape: make a special character literal\. matches a real dot

Two pieces cause most beginner bugs. First, . is special — to match a literal dot in example.com you must write example\.com, or your pattern also matches exampleXcom. Second, a character class [.] needs no escaping inside the brackets — most characters lose their magic there.

How the engine actually matches: greedy, lazy and backtracking

A regex engine reads your pattern left to right and tries to match, one step at a time. When it hits a quantifier like .* it is greedy by default: it grabs as much as possible, then gives characters back one at a time until the rest of the pattern fits. That process — trying, failing, giving back — is called backtracking.

<p>first</p> <p>second</p>
Pattern: <p>.*</p>      → matches the WHOLE line (greedy)
Pattern: <p>.*?</p>     → matches <p>first</p> only (lazy)

Adding ? after a quantifier makes it lazy: match as little as possible. Greedy is the right default for “everything up to the end”; lazy is the right default for “the next closing tag”. Choosing wrong is the most common reason a pattern matches far more (or far less) than expected.

Catastrophic backtracking. A pattern such as (a+)+$ on a long string of a's can take effectively forever: the engine tries exponentially many ways to split the same characters. The rule: never nest quantifiers over overlapping choices, and prefer a specific pattern ([^<]*) over a vague one (.*) inside a repeated group.

Patterns worth memorising

Keep these as starting points — test each one against your real data before shipping it:

# A simple email check (good enough for a form hint, not proof)
\b[\w.+-]+@[\w-]+\.[\w.]+\b

# Date: YYYY-MM-DD
^\d{4}-\d{2}-\d{2}$

# North American phone number, flexible separators
^\+?1?[-. ]?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$

# A word, with its position: capture the username from user@host
^(?<user>[\w.+-]+)@(?<host>[\w-]+\.[\w.]+)$

# Lines starting with ERROR in a log file (multiline flag m)
^ERROR: (.*)$

Notice the email pattern is deliberately imperfect: the real standard for email addresses is so complicated that a single regex for “all valid emails” is hundreds of characters long and still wrong. The professional approach is a simple sanity check plus actually sending a confirmation email.

Flags: the switches that change everything

FlagEffect
gGlobal — find all matches, not just the first
iCase-insensitive — cat matches CAT
mMultiline — ^ and $ match at line starts/ends
sDot-all — . also matches newlines
uUnicode mode — correct handling of emoji and astral characters

The m flag surprises people most: without it, ^ERROR only matches at the very start of the whole text, not at the start of each line in a log file. If your pattern works on one line but not on a file, the missing m is the first thing to check.

Common mistakes

  • Using .* when you mean [^<]* or \S+. Vague patterns backtrack and over-match; specific ones are faster and safer.
  • Forgetting to escape ., (, + in literal text. file.txt as a pattern also matches fileatxt.
  • Validating email with one giant regex. Use a simple check, then verify by sending mail.
  • Parsing HTML or nested structures with regex. HTML is not a regular language — a parser is the right tool, and regex will break on the first nested tag.
  • Nested quantifiers like (a+)+ or (.*)*. The classic freeze. Rewrite with a single quantifier over a precise class.
  • Forgetting the g flag. In many tools only the first match is returned unless you ask for all of them.

Try it: Regex Tester

Every pattern in this guide is testable: paste it into the Regex Tester, type your own text underneath, and watch the matches highlight live — with each capture group listed.

Open the Regex Tester →

Keep learning

Frequently asked questions

Which regex flavour should I learn?

The core syntax is the same almost everywhere. JavaScript, Python, Java and Go agree on the basics in the table above; they differ at the edges (lookbehind, named-group syntax, Unicode handling). Learn the core, then check your language's docs for the edges — and test in the Regex Tester, which uses your browser's JavaScript engine.

What is a capture group, and why would I use one?

Parentheses do two jobs: they group part of a pattern, and by default they also capture what they matched, so you can reuse it — for example turning 2026-11-21 into 21/11/2026 with a replacement like $3/$2/$1. Use (?:…) when you only need grouping and don't want the capture.

Why is my regex slow or freezing the page?

Almost always catastrophic backtracking: nested quantifiers over overlapping choices, on a long input. Simplify the pattern, replace .* with a negated class, or add an anchor so the engine fails fast instead of trying every split.

What is the difference between * and +?

* means “zero or more” — the piece may be absent entirely. + means “one or more” — it must appear at least once. \d* matches an empty string; \d+ doesn't. That one-character difference is a frequent source of patterns that match when they shouldn't.

Can regex validate an email address properly?

No single practical regex covers the full standard — quoted strings, comments and unusual domains make it absurdly long. A short pattern plus a confirmation email is the professional answer; the regex is a typo-catcher, not a proof.