Browsers & softwarePractical guides

Regex replacement changed an ID? Check named groups and expected matches first

Before replacing identifiers in bulk, inspect the complete matches and capture groups, then check the resulting text. Two fictional IDs provide a small test for leading zeros, separators and missed records.

Lines of colorful code on a dark computer display
Illustrative photo: Barney Goodman · Unsplash License

Key Takeaways

Use a fixed input and expected-match list. A-001 B-002 should produce two complete matches. Replacing with $<team>:$2 gives A:001 B:002. Verify the replacement separately after the match-list test passes.

In this article

Reproduce the two-ID example

MDN’s named-group guide explains retrieving captures by name. In the regex tester, enter A-001 B-002 as the input and use the expression below with flag g.

Enter the expected complete matches as a JSON string array. After running, the team groups should be A and B and the second captures should be 001 and 002. Keeping them as text retains their padding.

Expression

(?<team>[A-Z])-(\d{3})
One uppercase letter followed by a hyphen and three digits.

Replacement and expected matches

Replacement: $<team>:$2
Expected matches: ["A-001","B-002"]
Reference replacement output: A:001 B:002.

Add a counterexample that should fail

Change the second ID to B-02 and keep the original expected list. The three-digit pattern misses it, so the expected-match test fails. Establish the permitted identifier length before correcting the record or revising the expression.

If the rules allow two or three digits, use \d{2,3} for that part and update the expected list to reflect the actual input. Keep both versions. Consult the JavaScript replacement rules for numbered and named substitutions and confirm syntax when moving to another application.

Keep match evidence and the final text

For configuration work, follow the semantic checks after editing. The JSON and evidence guide explains how to define what each validation step establishes.

  1. Inspect complete matches, ranges and groups. Check unexpected matches and empty results.
  2. Compare the replacement with A:001 B:002. The expected-match test checks its list; review the replacement against the intended task too.
  3. Download the JSON review and save the original input separately alongside it. Keep the expression and result, then rerun the small test when the expression changes.

Further reading & sources

Put the guide into practice

Open the relevant tool, preview the result and check your exported file.