Substitution in Regex

Substitution in regex refers to the process of replacing matches of a pattern with a specified replacement string. It allows you to transform or modify text based on the matches found in the input string.

Substitution Description
$ number Includes the last substring matched by the capturing group that is identified by number, where number is a decimal value, in the replacement string
${ name } Includes the last substring matched by the named group that is designated by (? ) in the replacement string.
$$ Includes a single "$" literal in the replacement string.
$& Includes a copy of the entire match in the replacement string.
$` Includes all the text of the input string before the match in the replacement string.
$' Includes all the text of the input string after the match in the replacement string.
$+ Includes the last group captured in the replacement string.
$_ Includes the entire input string in the replacement string.

You can replace a string using regex backreference using a string replacement function/method provided by the programming language or tool you are using.

The following example demonstrate how you can replace a string using regex backreference in JavaScript:

Example: Regex Substitution in JavaScript
var regexPattern = /(Hello)/;
var str = 'Hello World!';

//replaces Hello with Hi
var newstr = str.replace(regexPattern, 'Hi');

console.log(newstr);  //output: 'Hi World!'

Replace String using Backreference

You can replace string by taking reference of the matched group using $. Use the respective matched group number e.g. $1 for first group, $2 for second and so on.

The following uses backreference $1, $2, $3, and $4 for the captured groups and add - between each matched group.

Example: Regex Substitution in JavaScript
//captures first digit as group#1, second three digits as group#2 
//and four digits as group#3 and last four digits as group#4 
var regexPattern = /(\d)(\d{3})(\d{3})(\d{4})/;
var str = '+12015645555';

//adding - between each group
var newstr = str.replace(regexPattern, '$1-$2-$3-$4');  

console.log(newstr);//output: +1-201-564-5555

In the regex pattern, (\d) finds one digit as a group, (\d{3}) as a second group, (\d{3}) as a third group, and (\d{4}) as a fourth group which can be referenced using $1, $2, $3 and $4 respectively.

Note: There might be slight variations in implementing substitutions based on the programming language you are using.