| Replacement Text Tutorial |
| Introduction |
| Characters |
| Non-Printable Characters |
| Matched Text |
| Backreferences |
| Match Context |
| Case Conversion |
| Conditionals |
| Control Verb Argument |
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, Google Sheets, Delphi, .NET, Java, ICU, PCRE2, PHP, and XPath. \0 works with the JGsoft applications, Delphi, Ruby, PHP, RE2, 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.
If you find the content on this website helpful they you may want a copy you can read offline or even print, or browse the site as often as you want without ads. You can purchase your own copy of the Regular-Expressions.info printable PDF download. As a bonus, you'll get a lifetime of advertisement-free access to this site!
| Quick Start | Tutorial | Search & Replace | Tools & Languages | Examples | Reference |
| Introduction | Characters | Non-Printable Characters | Matched Text | Backreferences | Match Context | Case Conversion | Conditionals | Control Verb Argument |
Page URL: https://www.regular-expressions.info/replacematch.html
Page last updated: 18 June 2025
Site last updated: 18 August 2026
Copyright © 2003-2026 Jan Goyvaerts. All rights reserved.