XML technologies / Regular expressions / Extended introductory examples / Modifying text with regular expressions
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
So far, the examples have focused on finding text and⟦U+0003⟧extracting information from the examined string. Now we consider substitution, or search and replace, a regex feature supported by Perl and many other regex tools.
As we saw, $var =~ m/Regex/ applies the regex to the text in the variable and returns true or false. The similar construct $var =~ s/Regex/Ersatztext/ goes further: if the regex matches, the matching portion of the string in $var is replaced by the Ersatztext between the middle and final slashes. The regex is the same as in m/.../, but replacement text is treated like a double-quoted string. Variables can therefore appear in it, including the especially useful $1, $2 and so on, which refer to substrings just matched.
With $var =~ s/.../.../, the variable changes only if the regex matches; otherwise it remains unchanged. For example, if $var contains text Jeff●Friedl and we apply
$var =~ s/Jeff/Jeffrey/;, then $var becomes Jeffrey●Friedl. If variable $var previously contained Jeffrey●Friedl, this code would instead produce Jeffreyrey●Friedl. Word-boundary metacharacters are needed! In Introduction to regular expressions, we saw that in some versions of egrep ˹\<˼ and ˹\>˼ are supported as word-start and word-end metacharacters. Perl instead uses a single ˹\b˼ for both:
$var =~ s/\bJeff\b/Jeffrey/;A tricky question: just as with m/.../, for s/.../.../ modi⟦U+0002⟧fiers such as /i are also allowed. What does substitution $var =~ s/\bJeff\b/Jeff/i do here? For the answer, see Answer 7.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln
back to top