2.22. Insert Match Context into the Replacement Text

Problem

Create replacement text that replaces the regex match with the text before the regex match, followed by the whole subject text, followed by the text after the regex match. For example, if Match is found in BeforeMatchAfter, replace the match with BeforeBeforeMatchAfterAfter, yielding the new text BeforeBeforeBeforeMatchAfterAfterAfter.

Solution

$`$_$'
Replacement text flavors: .NET, Perl
\`\`\&\'\'
Replacement text flavor: Ruby
$`$`$&$'$'
Replacement text flavor: JavaScript

Discussion

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 ...

Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.