Regular Expressions

A compact pattern language for matching text: literals, character classes, quantifiers, anchors, groups, greedy vs lazy, and ReDoS.

What is it?

A regular expression (regex) is a pattern that describes a set of strings. You use it to test whether text matches, find matches inside text, extract parts, or replace them.

The building blocks:

- Literals: cat matches the characters c, a, t in order. - Character classes: [aeiou] any vowel, [0-9] any digit, [^0-9] anything but a digit. Shorthands: \d digit, \w word character, \s whitespace, . any character except newline. - Quantifiers: * zero or more, + one or more, ? zero or one, {2,4} between two and four. - Anchors: ^ start, $ end, \b word boundary. They match positions, not characters. - Groups: ( … ) group a sub-pattern and capture what it matched; (?: … ) groups without capturing; (?<name> … ) names the capture. | means "or".

Quantifiers are greedy by default (match as much as possible). Adding ? makes them lazy (as little as possible). Badly built patterns can take exponential time on certain inputs (catastrophic backtracking), which attackers exploit as ReDoS (regular expression denial of service).

Explain like I'm 10

A regex is a stencil you slide along the text: wherever the text fits the stencil's shape, you have a match. Character classes are holes that accept several letters, quantifiers are holes that stretch, and anchors pin the stencil to the edge of the page.

Examples

Testing and extracting with groups (JavaScript)

const datePattern = /^(\d{4})-(\d{2})-(\d{2})$/;

console.log(datePattern.test("2024-03-15"));   // true
console.log(datePattern.test("15/03/2024"));   // false

const match = "2024-03-15".match(datePattern);
const [, year, month, day] = match;            // skip the full match at [0]
console.log(year, month, day);                 // "2024" "03" "15"

// Named groups read better
const named = /(?<year>\d{4})-(?<month>\d{2})/.exec("Due 2024-03");
console.log(named.groups.year);                // "2024"

Greedy vs lazy, and find-all (Python)

import re

html = "<b>bold</b> and <i>italic</i>"

print(re.findall(r"<.+>", html))    # ['<b>bold</b> and <i>italic</i>']  greedy
print(re.findall(r"<.+?>", html))   # ['<b>', '</b>', '<i>', '</i>']     lazy

log = "ERROR 2024-03-15 disk full; WARN 2024-03-16 cpu high"
for level, date in re.findall(r"(ERROR|WARN) (\d{4}-\d{2}-\d{2})", log):
    print(level, date)
# ERROR 2024-03-15
# WARN 2024-03-16

print(re.sub(r"\s+", " ", "too    many   spaces"))  # 'too many spaces'

Use raw strings (r"...") in Python so backslashes reach the regex engine unchanged. Use regex for small tag-like patterns as shown, but parse real HTML with an HTML parser.

Catastrophic backtracking (ReDoS)

const evil = /^(a+)+$/;

evil.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");   // true, instantly
evil.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!");   // false, but after ~2^29 attempts:
                                               // can freeze the thread for seconds

const safe = /^a+$/;                           // same language, no nested quantifier
safe.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!");   // false, instantly

(a+)+ gives the engine exponentially many ways to split the a's between the inner and outer loop, and it tries every one before giving up. Avoid nested quantifiers over overlapping patterns, limit input length, or use a linear-time engine (Go's regexp, Rust's regex crate, RE2).

How it works

Most engines in JavaScript, Python, Java, Perl, PCRE and .NET are backtracking engines. They walk the pattern left to right; when a choice point (a quantifier or an alternation) fails later on, they back up and try the next option. That supports powerful features like backreferences (\1) and lookarounds ((?=…)), but in the worst case the number of paths grows exponentially.

Greedy quantifiers first take as much as possible, then give back one character at a time if the rest of the pattern fails. Lazy ones start with as little as possible and take more only when needed. Both find a match if one exists; they differ in which match they pick.

Another family, used by RE2, Go and Rust, compiles the pattern into a finite automaton and scans the input once, guaranteeing time linear in the input length. The trade-off is no backreferences and, in some engines, no lookarounds.

Flags change behaviour: i case-insensitive, g global (all matches, JavaScript), m makes ^/$ match at line breaks, s lets . match newlines, u enables full Unicode handling in JavaScript.

Pattern ^(\d{4})-(\d{2})$ against "2024-03"

  ^        position 0           ok
  (\d{4})  "2024"               group 1 = "2024"
  -        "-"                  ok
  (\d{2})  "03"                 group 2 = "03"
  $        end of string        ok  -> match

  Greedy  <.+>   on "<b>x</b>"  ->  "<b>x</b>"   (longest)
  Lazy    <.+?>  on "<b>x</b>"  ->  "<b>"        (shortest first)

Why does it exist?

Searching and validating text is everywhere: log analysis, input validation, find-and-replace in editors, tokenising, data cleanup. Writing a hand-made loop for each pattern is long and error-prone. Regular expressions, from Stephen Kleene's 1950s formal language theory and popularised by Unix tools like grep, sed and Perl, give a compact, portable notation for it.

When to use it

Use regex for flat, well-defined text patterns: validating formats (postal codes, ISO dates, simple identifiers), extracting fields from log lines, search-and-replace across files, splitting on complex delimiters, and quick checks in editors and the command line.

When not to use it

Don't parse nested or recursive structures (HTML, JSON, programming languages) with regex: use a real parser. Don't use a regex to fully validate email addresses or URLs; use a URL parser, or a simple sanity check followed by a verification step. When a simple string method (startsWith, includes, split) does the job, it's clearer and faster. Avoid running backtracking regex on untrusted, unbounded input.

Common mistakes

  • Forgetting anchors, so /\d{3}/ 'validates' a string like abc12345xyz because it matches somewhere inside it.

  • Using a greedy .* and matching far more than intended; use a lazy .*? or a negated class like [^"]*.

  • Not escaping special characters (., ?, +, (, $) when matching them literally, e.g. using . to match a dot.

  • Writing nested quantifiers like (a+)+ or (.*)* that can backtrack catastrophically on crafted input (ReDoS).

  • In Python, writing patterns in normal strings instead of raw strings, so \b becomes a backspace character.

Practice exercises

  1. Easy:

    Write a regex that matches a US-style ZIP code: exactly 5 digits, optionally followed by a hyphen and 4 more digits. Test it against valid and invalid examples.

  2. Medium:

    From log lines like 2024-03-15 12:01:09 [ERROR] (auth) Login failed, extract the date, level and module with named groups, and count errors per module.

  3. Hard:

    Find a regex that hangs on a 30-character input, measure how long it takes as the input grows by one character at a time, then rewrite it to match the same strings in linear time.

Interview questions

What is the difference between greedy and lazy quantifiers?

Greedy quantifiers (*, +, {n,}) match as much as possible and give back characters only if the rest of the pattern fails. Lazy quantifiers (*?, +?) match as little as possible and expand only when needed.

What do `^` and ` Regular Expressions · Programming Fundamentals · Zykit do?

They're anchors matching the start and end of the input (or of each line with the multiline flag). They match positions, not characters, and are essential for validating that a whole string fits a pattern.

What is a capture group, and what is a non-capturing group?

( … ) groups part of a pattern and remembers the text it matched, so you can extract or backreference it. (?: … ) groups for quantifiers or alternation without capturing, which keeps group numbering clean and is slightly faster.

What is catastrophic backtracking?

Exponential run time in a backtracking regex engine when a pattern offers many overlapping ways to match the same text (e.g. (a+)+$) and the overall match fails, so the engine tries every combination.

What is ReDoS and how do you prevent it?

Regular expression denial of service: an attacker sends input that triggers catastrophic backtracking, tying up CPU. Prevent it by avoiding nested or overlapping quantifiers, limiting input length, using timeouts, or using a linear-time engine like RE2 or Rust's regex crate.

What do `\d`, `\w` and `\s` match?

\d a digit, \w a word character (letters, digits, underscore) and \s a whitespace character. Their uppercase forms (\D, \W, \S) match the opposite. With Unicode modes they may include non-ASCII digits and letters.

What is a lookahead?

A zero-width assertion that checks what follows without consuming it: (?=…) positive, (?!…) negative. For example \d+(?=px) matches the digits in '12px' but not the 'px'.

Why shouldn't you parse HTML with regex?

HTML is nested and irregular (attributes in any order, comments, self-closing tags, malformed markup). Regular expressions can't track arbitrary nesting, so regex-based parsing is fragile; an HTML parser handles these cases correctly.

Why should Python regex patterns be raw strings?

In normal Python strings, backslash sequences like \b or \1 are interpreted by Python before the regex engine sees them (\b becomes a backspace). A raw string r"\b" passes the backslash through unchanged.

How do backtracking and automaton-based engines differ?

Backtracking engines (PCRE, JavaScript, Python, Java) try alternatives recursively and support backreferences and lookarounds, but can take exponential time. Automaton-based engines (RE2, Go, Rust) guarantee linear time in the input length but drop features like backreferences.