XML technologies / Regular expressions / Java / Using java.util.regex
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Regular-expression handling in java.util.regex is straightforward. The package contains just two classes, an interface and an exception:
java.util.regex.Pattern
java.util.regex.Matcher
java.util.regex.MatchResult
java.util.regex.PatternSyntaxException I will refer to the first two classes simply as “Pattern” and “Matcher”. Often, we use only these two. The Pattern object is a compiled regex applicable to any string. Each application uses a Matcher object, an instance of it, connecting the Pattern object to the input string.
Since Java 1.5, class MatchResult encapsulates the results of a successful match. Matcher also stores these data, but only until the next search; they can be saved as a MatchResult.
Exception PatternSyntaxException is thrown when compiling a regex produces an error, for example invalid syntax such as ˹[hoppla)˼. The exception derives from java.lang.IllegalArgumentException and is not caught.
The following program performs a simple match:
public class SimpleRegexTest {
public static void main(String[] args)
{
String beispielText = "nur 1mal kurz testen.";
String beispielRegex = "\\d+\\w+"; // entspricht \d+\w+
java.util.regex.Pattern p = java.util.regex.Pattern.compile(beispielRegex);
java.util.regex.Matcher m = p.matcher(beispielText);
if (m.find()) {
String trefferText = m.group();
int trefferStart = m.start();
int trefferEnde = m.end();
System.out.println("Treffer [" + trefferText + "] "
"von " + trefferStart +
" bis " + trefferEnde + ".");
} else {
System.out.println("Kein Treffer.");
}
}
}It prints ›Treffer [1mal] von 4 bis 8.‹. As in all this chapter’s examples, user-chosen names are italicized. Bold portions can be omitted if the program header contains
import java.util.regex.*;, as in the examples in Features and dialects (see Using regular expressions in Java).
This makes the code clearer and is standard practice. The remaining examples assume this import statement is present.
The object model of java.util.regex differs somewhat from the usual model. Notice how the example creates a Matcher object m by connecting the Pattern object to the input string. This Matcher object triggers matching with method find() and reads match data with methods group(), start and end and so on.
This approach seems a little cumbersome, but we will soon get used to it.
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