Regular expressions and text guides
Regex replacement: reorder captured groups
Use numbered captures, global replacement and literal dollar signs without mixing pattern and replacement syntax.
Capture the pieces
Parentheses capture matched text. In a JavaScript replacement string, $1 refers to the first capture and $2 to the second.
Reorder one known date-like value before processing a document. This example transforms text; it does not validate that the date exists.
Pattern: (\d{4})-(\d{2})-(\d{2})
Replace: $3/$2/$1
2024-01-09 → 09/01/2024Select all matches deliberately
Without g, JavaScript regex replacement changes only the first match. With g, it changes every non-overlapping match.
Test two occurrences and one nonmatching line. A successful single-occurrence fixture cannot reveal a missing global flag.
Use replacement escapes
The replacement field is not another regular expression. JavaScript uses $ for a literal dollar sign and
amp; for the full match.Backslash-number replacement syntax from another language may not mean the same thing here. Check the target engine before copying a recipe.
Input: price=10
Pattern: \d+
Replacement: $amp;
Output: price=$10Review changed and unchanged text
Inspect the complete output in Text Diff after replacement. Broad matches can modify IDs, filenames or quoted values unintentionally.
For structured JSON or CSV, use a parser and field transformation when possible. Regex replacement cannot preserve every nested or quoted format reliably.