Glossary

Regex

A regular expression (regex) is a compact pattern-matching language for describing sets of strings — used to search, validate, split, or extract text. Nearly every programming language ships a regex engine, and while dialects differ slightly, the core syntax (literals, character classes, quantifiers, anchors) is shared across almost all of them.

How it works

A regex is built from a small set of building blocks:

  • Literals — ordinary characters match themselves (cat matches "cat").
  • Character classes — [abc] matches one of a, b, or c; \d, \w, \s are shorthand for digits, word characters, and whitespace.
  • Quantifiers — * (0+), + (1+), ? (0 or 1), {n,m} (between n and m repetitions) control how many times the preceding token repeats.
  • Anchors — ^ and $ pin a match to the start or end of a line/string; \b marks a word boundary.
  • Groups and alternation — (...) groups a sub-pattern (see capture group); | means "or".
  • Assertions — lookahead and lookbehind check what's next to a position without consuming it.

Most engines are backtracking-based: they try a path, and if it fails, they backtrack and try another. This makes some patterns — especially nested quantifiers like (a+)+ — vulnerable to catastrophic backtracking, where a crafted input causes exponential-time matching (a common denial-of-service vector, ReDoS).

Example:

Pattern: ^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$
Matches: "user.name+tag@example.com"

Common pitfalls

  • . matches almost any character by default — remember to escape it (\.) when you mean a literal dot.
  • Greedy quantifiers (.) grab as much as possible before backtracking; use the lazy form (.?) when you want the shortest match.
  • Nested, overlapping quantifiers can cause catastrophic backtracking on adversarial input — a real security risk for user-supplied patterns or input.
  • "Validating" emails or URLs with a hand-rolled regex is notoriously unreliable — the specs allow far more (and stranger) syntax than most patterns account for.

Related terms

  • Capture group — parenthesized sub-patterns used to extract or backreference part of a match.
  • Lookahead — a zero-width assertion for checking what follows a position without consuming it.

See also

  • Tool: Regex Tester — test patterns with real-time match highlighting, capture groups, and a built-in cheat sheet.