XML technologies / Regular expressions / Extended introductory examples
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Remember the doubled-word problem from Introduction to regular expressions? I said that a language such as Perl could implement a complete solution in just a few lines. Such a solution might look like this:
$/ = ".\n";
while (<>) {
next if !s/\b([az]+)((?:\s|<[^>]+>)+)(\1\b)/\e[7m$1\e[m$2\e[7m$3\e[m/ig;
s/^(?:[^\e]*\n)+//mg; # Nicht markierte Zeilen löschen.
s/^/$ARGV: /mg; # Dateinamen voranstellen.
print;
}Yes, that is the entire program.
Even if you know Perl, I do not expect you to understand this immediately (at least not yet!). I only wanted to show an example going beyond egrep and whet your appetite for serious regex applications. The important parts are the three regular expressions:
˹
\b([az]+)((?:\s|<[^>]+>)+)(\1\b)˼˹
^(?:[^\e]*\n)+˼˹
^˼
Although this example uses Perl, its three regexes can be used unchanged or with small adjustments in other languages, such as PHP, Python, Java, Visual Basic .NET, Tcl and others.
The last regex, ˹^˼, is probably clear, but the others remain difficult to understand with knowledge limited to egrep . Perl’s regex dialect differs from that of egrep. Some metacharacters differ, and Perl, like most modern tools, has many more. This chapter offers many examples.
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