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:
$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
In this same example, we can also use
$& 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
Named capture group example:
if you want to reproduce, please indicate the source:
regex – Substitutions with Regular Expressions – Basics of Substitution - CodeDay