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 http://\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.
Did this website just save you a trip to the bookstore? Please make a donation to support this site, and you'll get a lifetime of advertisement-free access to this site!
Page URL: https://www.regular-expressions.info/replacematch.html
Page last updated: 01 December 2016
Site last updated: 23 August 2019
Copyright © 2003-2019 Jan Goyvaerts. All rights reserved.
|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|