XML technologies / Regular expressions / Java / The Matcher object / Chaining methods
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The following fragment creates a Matcher and sets some options:
Pattern p = Pattern.compile(regex); // Regex kompilieren.
Matcher m = p.matcher(text); // Regex mit dem Suchtext verbinden -> Matcher.
m.region(5, text.length()); // Region vom 5. Zeichen bis zum Ende.
m.useAnchoringBounds(false); // ˹^˼ usw. sollen nicht auf die Regionsgrenzen passen.
m.useTransparentBounds(true); // »Look«-Konstrukte blicken über die Grenzen hinaus.Earlier examples showed that we need the Pattern object only to create the Matcher and never afterward, which is very common. We can therefore combine the first two lines:
Matcher m = Pattern.compile(regex).matcher(text);
m.region(5, text.length()); // Region vom 5. Zeichen bis zum Ende.
m.useAnchoringBounds(false); // ˹^˼ usw. sollen nicht auf die Regionsgrenzen passen.
m.useTransparentBounds(true); // »Look«-Konstrukte blicken über die Grenzen hinaus.Since the next two Matcher methods both return the Matcher object, all calls can even be written on one line, wrapped here for readability:
Matcher m = Pattern.compile(regex).matcher(text).region(5,text.length())
.useAnchoringBounds(false).useTransparentBounds(true);This does exactly the same thing much more concisely. Detailed comments like those in the first version are harder to insert, but good comments should explain not simply what happens, but rather why it is done that way. For example, the program described in “ A Matcher for checking HTML with multiple patterns ” becomes clearer and easier to read through method chaining.
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