Historical notebook 10 min read

Regular Expressions: a Basic Guide

The 2006 guide to regular expressions, with a new chapter: one badly written regex can stall a server.

Author: Vincenzo Lombino
#ComputerScience#Regex#Performance

1. Practical Foundations: Validating a Web Form

Regular expressions (regex) are an indispensable tool for software developers: they describe string patterns exhibiting formal regularity, collapsing dozens of procedural validations into a single concise expression.

In the practical tutorial «Espressioni Regolari (Guida Base)», the practical baseline was a ubiquitous web application task: validating user form inputs:

  • First Name: single word, alphabetic letters only (including accented characters), optional: ^[a-zA-Zàòèéùì]*$
  • Last Name: one or more words, letters, spaces, and apostrophes, required: ^[a-zA-Zàòèéùì' ]+$
  • Email: alphanumeric prefix with periods/underscores, @ symbol, domain name, and 2-to-4 letter TLD: ^[a-zA-Z0-9_.]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}$
  • Phone Number: dialing code and subscriber number separated by hyphen: ^[0-9]+-[0-9]+$

2. The Developer Toolbox: Classes, Ranges, Quantifiers, and Anchors

Constructing reliable expressions relies on core building blocks:

  • Character classes [...] and range operator -: square brackets match a single occurrence of any character within the set. The hyphen specifies ordered ranges: [a-z] for lowercase, [0-9] for digits, or composite sets like [a-fA-F0-9] for hexadecimal values.
  • Repetition quantifiers: asterisk * matches zero or more occurrences (admitting empty sets for optional inputs); plus + mandates one or more occurrences; curly brackets {min,max} define exact thresholds, such as [0-9]{3,4}-[0-9]{7}.
  • Escape character \: prefixing metacharacters (such as \., \-, or \/) disables their operational function, evaluating them as literals.
  • Anchors ^ and $: ^ enforces matching from the string start and $ at the end. Without anchors, [0-9]+ matches partially inside abc123xyz, invalidating the integrity check.

3. The Greedy Trap: Greedy Quantifiers vs. Negated Classes

Repetition quantifiers are greedy by default: they consume the longest possible character sequence matching the pattern.

Applying <.+> to an HTML string:

html
<HTML><HEAD><TITLE>REGULAR EXPRESSIONS</TITLE></HEAD><BODY></BODY></HTML>

fails to match individual tags: it consumes everything from the first < to the final > across the line, swallowing the entire markup structure.

Two distinct remedies exist with fundamentally different runtime profiles:

  • Reluctant quantifier <.+?>: halts at the first >, but incurs step-by-step backtracking.
  • Negated character class <[^<>]+>: explicitly states that any character except < or > may appear. The state machine proceeds linearly without ambiguity.

Similarly, isolating sentences ending in a period is written as [^.]+, leveraging character class negation via ^ inside brackets.

If a routine merely strips whitespace or checks string prefixes, avoid regular expressions entirely: native string functions (includes, indexOf, replaceAll) are an order of magnitude faster and carry zero algorithmic risk.

4. Production Outages: ReDoS and Catastrophic Backtracking

Most modern programming languages (PHP, JavaScript, Python) rely on Non-deterministic Finite Automata (NFA) regex engines. When patterns contain nested quantifiers or overlapping alternations—such as ^(a+)+$ or (a|a+)+$—the engine explores permutations recursively.

On valid input like aaaaa, evaluation is instantaneous. But when presented with non-matching strings—such as thirty a characters followed by an exclamation mark aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!—the NFA engine explores every branch before failing.

Computational steps explode exponentially in O(2n). On an input of merely 30 characters, evaluation exceeds a billion operations, pinning a CPU core at 100% for minutes.

This vulnerability, known as Regular Expression Denial of Service (ReDoS), is not theoretical: on July 2, 2019, a single regex rule with catastrophic backtracking (.*.*=.*) deployed to Cloudflare's WAF pinned edge server CPUs globally, causing a 27-minute worldwide outage.

5. The AI Era: Decision Models, Data Extraction, and the Math Under the Hood

Until recently, early language models had a famous blind spot: they could not reliably count how many times the letter 'r' appeared in strawberry. The reason is simple: they process subword tokens rather than individual characters. For decades, engineers wrote brittle regular expressions packed with lookarounds to pull fields out of messy documents.

With modern reasoning architectures and decision models, that workflow changed. Contemporary models grasp context, fix typos, and normalize chaotic text far better than any fixed pattern. At first glance, regular expressions might look obsolete.

Yet AI still relies on them under the hood for two core mechanics:

  • Tokenization and pre-processing: tokenizers powering leading models (such as BPE in tiktoken) split raw character streams with compiled regular expressions before any tensor math runs.
  • Structured Outputs and constrained decoding: when an LLM has to emit valid JSON matching a strict schema (via Outlines, vLLM, or Structured Outputs APIs), the runtime compiles that regex schema into a Deterministic Finite Automaton (DFA). At every generation step, the DFA masks logits so syntax-violating tokens drop to zero probability.

This brings a clear lesson for engineering leadership: knowing computer science basics lets you ask AI better questions.

Delegating everything to the prompt—feeding a 50MB log file into the context window to extract fields token by token—burns money, adds minutes of latency, and invites hallucinations. A stronger engineer uses the model on a small sample to spot the invariant structure and generate deterministic code (a linear DFA, native string ops, or a backtracking-safe regex) that processes millions of records locally at zero marginal cost.