CodeCraft
← Back to Blog
Patterns2026-04-09·12 min read

Regular Expressions: A Practical Developer's Guide

#regex#pattern-matching#validation#javascript
C
CodeCraft Team· Engineering

Regular expressions — regex for short — are one of the most powerful and most feared tools in a developer's toolkit. A single regex can validate an email address, extract all URLs from a document, replace complex patterns in code, or parse structured text in ways that would take hundreds of lines of manual string handling.

This guide builds your regex intuition from the ground up, culminating in real-world patterns you can use immediately in your projects.

The Basics: Literals and Metacharacters

The simplest regex is a literal string: /cat/ matches the exact text "cat". This is rarely interesting by itself — the power comes from metacharacters.

Character classes:

- . — Matches any single character except newline

- \d — Matches any digit (0–9). Equivalent to [0-9]

- \w — Matches any word character: letters, digits, underscore. Equivalent to [a-zA-Z0-9_]

- \s — Matches any whitespace (space, tab, newline)

- \D, \W, \S — Uppercase versions match the opposite (non-digit, non-word, non-whitespace)

Custom character classes — use square brackets:

- [aeiou] — matches any vowel

- [A-Z] — any uppercase letter

- [^0-9] — any non-digit (^ inside brackets means "not")

- [a-zA-Z_$][a-zA-Z0-9_$]* — valid JavaScript identifier

Anchors: Controlling Where Matches Occur

Without anchors, a regex matches anywhere in the string. Anchors specify where in the string the match must occur.

- ^ — Start of string (or start of each line in multiline mode)

- $ — End of string (or end of each line in multiline mode)

- \b — Word boundary (transition between word and non-word character)

- \B — Non-word boundary

Examples:

/^hello/     matches "hello world" but NOT "say hello"
/world$/     matches "hello world" but NOT "worldwide"
/\bcat\b/   matches "the cat sat" but NOT "catalog" or "concatenate"

Multiline mode (m flag): In JavaScript /pattern/m, ^ and $ match the start/end of each line, not just the whole string. Essential when processing multi-line text.

Quantifiers: How Many Times?

Quantifiers specify how many times the preceding element must match.

| Quantifier | Meaning |

|-----------|---------|

| * | 0 or more times |

| + | 1 or more times |

| ? | 0 or 1 times (optional) |

| {n} | Exactly n times |

| {n,} | n or more times |

| {n,m} | Between n and m times |

Examples:

/\d+/         matches "42", "1000", but NOT ""
/colou?r/     matches both "color" and "colour"
/\d{4}/       matches exactly 4 digits, like a year
/\d{2,4}/     matches 2, 3, or 4 digits

Greedy vs Lazy: By default, quantifiers are greedy — they match as many characters as possible. Add ? after a quantifier to make it lazy (match as few as possible):

/<.+>/   matches the entire "<b>bold</b> text" (greedy)
/<.+?>/  matches only "<b>" (lazy)

Groups and Capturing

Parentheses () group expressions and capture the matched text.

Capturing groups: /(\d{4})-(\d{2})-(\d{2})/ matches a date and captures year, month, day separately.

const match = "2024-05-09".match(/(\d{4})-(\d{2})-(\d{2})/);
match[0] // "2024-05-09" — full match
match[1] // "2024" — year
match[2] // "05" — month
match[3] // "09" — day

Named groups (more readable): /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/

const { year, month, day } = "2024-05-09".match(
  /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
).groups;

Non-capturing groups (?:...): Group without capturing — use when you need grouping for quantifiers or alternation but don't need the captured value.

Backreferences \1, \2: Refer back to a captured group. Useful for finding duplicated words: /\b(\w+)\s+\1\b/ matches "the the" or "hello hello".

Alternation and Lookaheads

Alternation |: Matches either the left or right expression.

/cat|dog/     matches "cat" or "dog"
/https?:\/\/(www\.)?/   matches "http://", "https://", "http://www.", "https://www."

Lookaheads — match only if followed/not followed by something, without consuming characters:

- (?=...) — Positive lookahead: /\d+(?= dollars)/ matches the number only if followed by " dollars"

- (?!...) — Negative lookahead: /\d+(?! EUR)/ matches numbers NOT followed by " EUR"

Lookbehinds (check what comes before):

- (?<=...) — Positive lookbehind: /(?<=\$)\d+/ matches digits preceded by $

- (?<!...) — Negative lookbehind

// Extract numbers that are prices (preceded by $)
"The item costs $42 and the tax is 3".match(/(?<=\$)\d+/g)
// ["42"]

Flags: Controlling Match Behavior

In JavaScript, flags follow the closing slash: /pattern/flags

| Flag | Effect |

|------|--------|

| g | Global — find all matches, not just the first |

| i | Case-insensitive: /hello/i matches "Hello", "HELLO" |

| m | Multiline: ^ and $ match line boundaries |

| s | DotAll: . matches newlines too |

| u | Unicode: enable full Unicode matching |

| v | Unicode sets (ES2024): advanced Unicode support |

// Find all email addresses (case-insensitive)
const emails = text.match(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi);

Real-World Patterns

Email address (simplified but practical):

/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

URL (basic):

/https?:\/\/[\w-]+(\.[\w-]+)+(\/[\w\-./?%&=]*)?/

IPv4 address:

/^(25[0-5]|2[0-4]\d|1?\d{1,2})(\.(25[0-5]|2[0-4]\d|1?\d{1,2})){3}$/

Date (YYYY-MM-DD):

/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/

Hex color:

/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/

Strong password (min 8 chars, requires uppercase, lowercase, number):

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/

Extract all links from HTML:

const hrefs = html.match(/href="([^"]+)"/gi)?.map(m => m.slice(6, -1));

Performance and Catastrophic Backtracking

Poorly written regex can cause exponential time complexity — a phenomenon called catastrophic backtracking. This has been exploited as a Denial-of-Service attack (ReDoS).

Vulnerable pattern example: /(a+)+b/ on input "aaaaaaaaaaaaaaa" (no 'b') causes the engine to try every possible grouping — exponential time.

Signs of a dangerous regex:

- Nested quantifiers: (a+)+

- Overlapping alternatives: (a|a?)+

- Very long input with no match

Mitigation:

- Use atomic groups or possessive quantifiers where available

- Test regex with tools that detect backtracking paths

- Use ReDoS checkers before deploying user-input regex in server code

- Set timeouts when running regex against user-controlled input

Regular expressions reward investment — they look intimidating at first but become a natural part of your thinking once internalized. Start with the simple patterns (character classes, quantifiers), build up to groups and lookaheads, and keep our real-world patterns section as a reference. Use our free Regex Tester to build, test, and debug your expressions against real input — with match highlighting and capture group inspection.