XML technologies / Regular expressions / Extended introductory examples / Modifying text with regular expressions / Code example: form letter
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
To illustrate variables in replacement text, consider a lighthearted example: a form-letter generator using this template:
Lieber =VORNAME=,
Sie haben einen =PLUNDER= gewonnen! Gratis!
Die ganze Familie =NACHNAME= freut sich über den =PLUNDER=!
Ja, =ARMLEUCHTER=, Sie Glücklicher! Beantworten Sie nur .....To personalize this for a recipient, the program would need data:
$vorn = "Tom";
$nachn = "Cruise";
$superpreis = "100% echten faux diamond";and would then fill in the template:
$brief =~ s/=VORNAME=/$vorn/g;
$brief =~ s/=NACHNAME=/$nachn/g;
$brief =~ s/=ARMLEUCHTER=/$vorn $nachn/g;
$brief =~ s/=PLUNDER=/wunderbaren $superpreis/g;Each substitution’s regex looks for a particular marker and replaces it with the desired text if found. In Perl, replacement text is treated like a double-quoted string, so it can contain interpolated variables, as in all four cases above. For example, the underlined part of s/=PLUNDER=/wunderbaren $superpreis/g is interpreted exactly like string "wunderbaren $superpreis". For a single letter, we would naturally insert the desired text directly. This method, however, automates the process, for example by reading names from a file.
The /g modi⟦U+0002⟧fier (g for “global”) is new. It makes s/.../.../ continue searching after a successful substitution, finding and replacing further matches. This is needed when a string contains the pattern several times and all occurrences should be replaced.
The result is predictable: a humorous version of a letter I have read far too often:
Lieber Tom,
Sie haben einen wunderbaren 100% echten faux diamond gewonnen! Gratis!
Die ganze Familie Cruise freut sich über den wunderbaren 100% echten faux diamond!
Ja, Tom Cruise, Sie Glücklicher! Beantworten Sie nur .....
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