|Replacement Text Tutorial|
|Regular Expressions Quick Start|
|Regular Expressions Tutorial|
|Replacement Strings Tutorial|
|Applications and Languages|
|Regular Expressions Examples|
|Regular Expressions Reference|
|Replacement Strings Reference|
|About This Site|
|RSS Feed & Blog|
Reinserting the entire regex match into the replacement text allows a search-and-replace to insert text before and after regular expression matches without really replacing anything. It also allows you to replace the regex match with something that contains the regex match. For example, you could replace all matches of the regex https?://\S+ with <a href="$&">$&</a> to turn all URLs in a file into HTML anchors that link to those URLs.
In Boost and std::regex your choice of replacement format changes the meaning of & and $&. When using the sed replacement format, & represents the whole regex match and $& is a literal dollar sign followed by the whole regex match. When using the default (ECMAScript) or “all” replacement format, & is a literal ampersand and $& represents the whole regex match.
The overall regex match is usually treated as an implied capturing group number zero. In many applications you can use the syntax for backreferences in the replacement text to reference group number zero and thus insert the whole regex match in the replacement text. You can do this with $0 in the JGsoft applications, Delphi, .NET, Java, XRegExp, PCRE2, PHP, and XPath. \0 works with the JGsoft applications, Delphi, Ruby, PHP, and Tcl.
Python does not support any of the above. In Python you can reinsert the whole regex match by using the syntax for named backreferences with group number zero: \g<0>. This also works in the JGsoft applications. Delphi does not support this, even though it supports named backreferences using this syntax.
Page URL: https://www.regular-expressions.info/replacematch.html
Page last updated: 12 August 2021
Site last updated: 02 December 2022
Copyright © 2003-2022 Jan Goyvaerts. All rights reserved.