Quick Start
Tools & Languages
Book Reviews
Replacement Text Tutorial
Non-Printable Characters
Matched Text
Match Context
Case Conversion
More on This Site
Regular Expressions Quick Start
Regular Expressions Tutorial
Replacement Strings Tutorial
Applications and Languages
Regular Expressions Examples
Regular Expressions Reference
Replacement Strings Reference
Book Reviews
Printable PDF
About This Site
RSS Feed & Blog

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 https?://\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.

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.