Regular Expressions Cookbook, 2nd Edition
by Steven Levithan
Published by
O'Reilly Media, Inc., 2012
and
Tags
| Replacement text flavors: .NET, Perl |
\`\`\&\'\'
| Replacement text flavor: Ruby |
$`$`$&$'$'
| Replacement text flavor: JavaScript |
The term context refers to the subject text that the regular expression was applied to. There are three pieces of context: the subject text before the regex match, the subject text after the regex match, and the whole subject text. The text before the match is sometimes called the left context, and the text after the match is correspondingly the right context. The whole subject text is the left context, the match, and the right context.
.NET and Perl support «$`», «$'», and «$_» to insert all three forms of context
into the replacement text. Actually, in Perl these are variables set
after a successful regex match and are available in any code until the
next match attempt. Dollar backtick is the left context. You can type
the backtick on a U.S. keyboard by pressing the key to the left of the 1
key in the top-left corner of your keyboard. Dollar straight quote is
the right context. The straight quote is the usual single quote. On a
U.S. keyboard, it sits between the semicolon and Enter keys. Dollar
underscore is the whole subject text. Like .NET and Perl, JavaScript
uses «$`» and «$'» for left and right context. However,
JavaScript does not have a token for inserting the entire subject text.
You can recompose the subject text by inserting the whole regex match
with «$&»
between the left and right context.
Ruby supports left and right context via «\`» and «\'», and uses «\&» to insert the whole regex match.
Like JavaScript, there is no token for the whole subject text.
Search and Replace with Regular Expressions in Chapter 1 describes the various replacement text flavors.
Recipe 3.15 explains how to use replacement text in source code.