How to Test a Regular Expression
AIGClub TeamShare
A useful regex test has positive cases, counterexamples, exact match ranges, expected groups, and a stated target engine. One successful sample is not a specification.
For browser JavaScript RegExp, test a pattern against matched, unmatched, empty, Unicode, and length-boundary samples. This interface accepts gimsuy, preserves literal spaces at both ends of the pattern, collects matches globally for preview, and caps output at 100 rows. Recheck the final expression in its deployment engine.
Practical steps
- For (?<code>\d{3}), use error 404 as a positive sample, error xx as a counterexample, and 4040 to decide whether anchors or word boundaries are required.
- Confirm that error 404 reports [6, 9), match 404, and named group code=404; then verify i, m, s, u, or y only when the requirement needs each flag.
- If replacement is part of the task, specify expected $1 or $<name> output. This UI treats an empty replacement field as no preview, not as delete-to-empty.
Boundaries and risks
This tester uses the current browser JavaScript engine, exposes gimsuy, adds global behavior internally for preview rows, and limits input/matches. It does not expose d or v, emulate PCRE/Python/Java/.NET, or prove that an accepted expression is free from catastrophic backtracking.
Recommended workflow
Write expected matches before editing the pattern. Add delimiters, blank fields, combining characters, astral Unicode, and long non-matching suffixes. Copy the final source and flags into project tests, then run target-runtime performance limits before release.
Frequently asked questions
- Why does pattern " a " not behave like pattern "a"?
- The spaces are literal input and are now preserved. Use \s only when whitespace is part of the requirement, and do not trim the pattern unless your application contract says to.
- Why are there multiple matches without a g flag?
- The preview adds global matching internally so it can list rows. Treat that as a display behavior and test the original flags in the calling code if single-match control flow matters.
- Which cases belong in the project test suite?
- Keep at least one intended match, one near miss, one empty or missing value, Unicode relevant to the field, maximum expected length, and a long adversarial non-match.