Frontend Utilities intermediate 12 min

Build a Regex That Catches the Right Inputs

Test a pattern against matching and non-matching examples before it becomes validation code.

Scenario

A form field should accept internal ticket IDs like OPS-1234 — uppercase OPS prefix, hyphen, four digits — and reject everything nearby: lowercase ops-1234, short OPS-12, other departments like ENG-9876. Writing the pattern from memory and shipping it is how OPS-99999 sneaks through six months later. A regex is a specification; test it against a deliberate set of should-match and should-fail examples before it guards anything.

Broken input

OPS-1234
ops-1234
OPS-12
ENG-9876
OPS-99999

Goal

Use Regex Tester to iterate on the pattern against live examples until exactly one of the five test lines matches. The negative cases are the specification — each one exists to kill a lazy pattern.

Tool sequence

  1. Open Regex Tester.
  2. Paste all five test lines and start naive: OPS-\d+ — the highlighting shows it wrongly accepts OPS-12, OPS-99999, and the tail of ops-1234.
  3. Pin the digit count with \d{4} and anchor both ends: ^OPS-\d{4}$.
  4. Re-check the highlights: only OPS-1234 matches. The anchors reject OPS-99999 (five digits), the literal OPS rejects ENG- and lowercase (no i flag set).
  5. Copy the final pattern into the validator, and keep the five test lines in a code comment or unit test — the next editor needs the same specification you just used.

Checkpoint output

/^OPS-\d{4}$/

OPS-1234   ✓ match
ops-1234   ✗ rejected (case)
OPS-12     ✗ rejected (too short)
ENG-9876   ✗ rejected (wrong prefix)
OPS-99999  ✗ rejected (too long)

One pattern, one intended match, four intentional rejections — the regex now encodes the actual ID format.

Common mistakes

  • Forgetting ^ and $, so OPS-1234 matches inside XOPS-12345 and partial garbage passes validation.
  • Testing only examples that should match — the bug is always in what should fail.
  • Reaching for .* or \d+ when the format specifies an exact width; precision is free at write time and expensive later.
  • Adding the i flag out of habit and re-accepting the lowercase prefix you meant to reject.

Related tools and lessons