Java Reference
In-Depth Information
Each of these methods returns boolean , with true meaning a match and false meaning no
match. To check whether a given string matches a given pattern, you need only type
something like the following:
Matcher m = Pattern . compile ( patt ). matcher ( line );
iif ( m . find ( )) {
System . out . println ( line + " matches " + patt )
}
But you may also want to extract the text that matched, which is the subject of the next re-
cipe.
The following recipes cover uses of this API. Initially, the examples just use arguments of
type String as the input source. Use of other CharSequence types is covered in Printing All
Occurrences of a Pattern .
Finding the Matching Text
Problem
You need to find the text that the regex matched.
Solution
Sometimes you need to know more than just whether a regex matched a string. In editors and
many other tools, you want to know exactly what characters were matched. Remember that
with quantifiers such as *, the length of the text that was matched may have no relationship
to the length of the pattern that matched it. Do not underestimate the mighty .* , which hap-
pily matches thousands or millions of characters if allowed to. As you saw in the previous re-
cipe, you can find out whether a given match succeeds just by using find() or matches() .
But in other applications, you will want to get the characters that the pattern matched.
After a successful call to one of the preceding methods, you can use these “information”
methods to get information on the match:
start(), end()
Returns the character position in the string of the starting and ending characters that
matched.
Search WWH ::




Custom Search