Replacement patterns enable you to replace all or part of the text that is matched in the input string. A replacement pattern can consist of one or more substitutions along with literal characters.
Usually, replacement patterns refer to (sub-) matches in the text. These matches can be defined as named groups or as groups without a name which are referenced by number in the seach pattern. For more information, see Grouping constructs.
(Sub-) matches are then replaced by referring to them in the replacement pattern. For more information about the avalable substitutions, see Substitutions.
Grouping constructs delineate subexpressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in the following table.
Grouping construct | Description | Pattern | Matches |
---|---|---|---|
( subexpression ) | Captures the matched subexpression and assigns it a zero-based ordinal number. | (\w)\1 | "ee" in "deep" |
(?< name > subexpression ) | Captures the matched subexpression into a named group. | (?<double>\w)\k<double> | "ee" in "deep" |
Substitutions are regular expression language elements that are supported in replacement patterns. The metacharacters listed in the following table are atomic zero-width assertions.
Character | Description | Pattern | Replacement pattern | Input string | Result string |
---|---|---|---|---|---|
$ number | Substitutes the substring matched by group number. | \b(\w+)(\s)(\w+)\b | $3$2$1 | "one two" | "two one" |
${ name } | Substitutes the substring matched by the named group name. | \b(?<word1>\w+)(\s)(?<word2>\w+)\b | ${word2} ${word1} | "one two" | "two one" |
$$ | Substitutes a literal "$". | \b(\d+)\s?USD | $$$1 | "103 USD" | "$103" |
$& | Substitutes a copy of the whole match. | (\$*(\d*(\.+\d+)?){1}) | **$& | "$1.30" | "**$1.30**" |
$` | Substitutes all the text of the input string before the match. | B+ | $` | "AABBCC" | "AAAACC" |
$' | Substitutes all the text of the input string after the match. | B+ | $' | "AABBCC" | "AACCCC" |
$+ | Substitutes the last group that was captured. | B+(C+) | $+ | "AABBCCDD" | AACCDD |
$_ | Substitutes the entire input string. | B+ | $_ | "AABBCC" | "AAAABBCCCC" |