Skip to content
ToolzKit

Guide · 7 min read

How regex testing works

Regular expressions are a small language for describing shapes in text. Written carefully they replace pages of parsing code; written carelessly they hang a server. Testing interactively against realistic input is the fastest way to tell which one you have written.

The flags that change everything

The global flag keeps searching after the first match. The case-insensitive flag ignores letter case. The multiline flag makes the caret and dollar anchor to each line rather than the whole string. The dot-all flag lets a dot match newlines. Most confusing regex behaviour turns out to be a missing or unexpected flag.

Greedy, lazy and why .* eats too much

Quantifiers are greedy by default: .* takes as much as it can and then gives characters back until the rest of the pattern fits. Adding a question mark makes it lazy, taking as little as possible. When a pattern matches far more text than you expected, greediness is usually the cause.

Capture groups and naming

Parentheses capture the text they match so you can extract or reuse it. Named groups make the intent obvious and survive reordering. If you only need grouping for alternation, use a non-capturing group so the numbering does not shift.

  • (\d{4})-(\d{2}) captures a year and a month by position.
  • (?<year>\d{4}) captures the same value by name.
  • (?:https?) groups without capturing.

Catastrophic backtracking

Nested quantifiers over overlapping character classes — the classic example being a repeated group that itself repeats — can force the engine through an exponential number of paths on input that nearly matches. The symptom is a pattern that is instant on short strings and freezes on a slightly longer one. Rewrite the pattern to remove the ambiguity rather than adding a timeout.

Know when to stop

Regex is a poor tool for nested structures. HTML, JSON and source code all have grammars that regular expressions cannot express. Use a real parser for those, and keep regex for lexical work: validation shapes, log line extraction, search and replace.