regex – Substitutions with Regular Expressions – Basics of Substitution

One of the most common and useful ways to replace text with regex is by using Capture Groups.
Or even a Named Capture Group, as a reference to store, or replace the data.

There are two terms pretty look alike in regex’s docs, so it may be important to never mix-up Substitutions (i.e. $1) with Backreferences (i.e. \1). Substitution terms are used in a replacement text; Backreferences, in the pure Regex expression. Even though some programming languages accept both for substitutions, it’s not encouraging.

Let’s we say we have this regex: /hello(\s+)world/i. Whenever $number is referenced (in this case, $1), the whitespaces matched by \s+ will be replaced instead.
The same result will be exposed with the regex: /hello(?<spaces>\s+)world/i. And as we have a named group here, we can also use ${spaces}.

In this same example, we can also use $0 or $& (Note: $& may be used as $+ instead, meaning to retrieve the LAST capture group in other regex engines), depending on the regex flavor you’re working with, to get the whole matched text. (i.e. $& shall return hEllo woRld for the string: hEllo woRld of Regex!)


Take a look at this simple example of substitution using John Lennon’s adapted quote by using the $number and the ${name} syntax:

Simple capture group example:
Substitution Example 1

Named capture group example:

Substitution Example 2

if you want to reproduce, please indicate the source:
regex – Substitutions with Regular Expressions – Basics of Substitution - CodeDay