Matched Text

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.

$& is substituted with the whole regex match in the replacement text in the JGsoft applications, Delphi, .NET, JavaScript, and VBScript. It is also the variable that holds the whole regex match in Perl. \& works in the JGsoft applications, Delphi, and Ruby. In Tcl, & all by itself represents the whole regex match, while $& is a literal dollar sign followed by the whole regex match, and \& is a literal ampersand.

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.

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.

Make a Donation

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! Credit cards, PayPal, and Bitcoin gladly accepted.