XML technologies / Regular expressions / Java / The Matcher object / Applying the regex: application
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
These are the main Matcher methods that initiate searches:
boolean find()
Applies the object’s regex to its input string and returns a Boolean indicating a match. Repeated calls find successive matches. Calling
find()without arguments restricts the search to the current region (see The Matcher region).A simple example:
String regex = "\\w+"; // \w+
String text = "Mastering Regular Expressions";
Matcher m = Pattern.compile(regex).matcher(text);
if (m.find())
System.out.println("match [" + m.group() + "]");This gives:
match [Mastering]
Replacing the
ifstatement withwhilemakes
while (m.find())
System.out.println("match [" + m.group() + "]");the program traverse the whole string and print every match:
match [Mastering] match [Regular] match [Expressions]
boolean find(int offset)
Calling
findwith a number starts the regex not at the string’s beginning, butoffsetcharacters later. If theoffsetis negative or exceeds the string’s length, exceptionIndexOutOfBoundsExceptionis thrown.This form of method
findignores the current region and instead resets it to the whole string before searching, internally callingreset(see Matcher reset()).In Answer 15 this form of
findis illustrated by an example.
boolean matches()
Returns a Boolean indicating whether the regex matches completely across the current region (see The Matcher region). A match must begin and end at the region’s boundaries. If the region covers the whole input, the default, this is equivalent to wrapping the regex in
˹\A...\z˼and may be more convenient.If the region covers only part of the string,
matchesmatches the entire region without requiring attention to flag anchoring bounds (see Anchoring bounds).Suppose a
CharBuffercontains text being edited. A mouse-selected area becomes the region. Clicking that selection could usem.usePattern(urlPattern).matches()to test whether it has URL syntax and trigger an action.This functionality is also available through method
matches()of classString:
"1234".matches("\\d+"); // wahr
"123!".matches("\\d+"); // falschboolean lookingAt()
Returns a Boolean indicating whether the regex matched within the current region starting at its beginning. It resembles
matches, but only the start of the match must align with the region’s start, not its end.
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