826 Part II: The Java Library
Here,patternis the regular expression that you want to use. Thecompile( )method transforms
the string inpatterninto a pattern that can be used for pattern matching by theMatcherclass.
It returns aPatternobject that contains the pattern.
Once you have created aPatternobject, you will use it to create aMatcher. This is done
by calling thematcher( )factory method defined byPattern. It is shown here:
Matcher matcher(CharSequencestr)
Herestris the character sequence that the pattern will be matched against. This is called the
input sequence.CharSequenceis an interface that defines a read-only set of characters. It is
implemented by theStringclass, among others. Thus, you can pass a string tomatcher( ).
Matcher
TheMatcherclass has no constructors. Instead, you create aMatcherby calling thematcher( )
factory method defined byPattern, as just explained. Once you have created aMatcher, you
will use its methods to perform various pattern matching operations.
The simplest pattern matching method ismatches( ), which simply determines whether
the character sequence matches the pattern. It is shown here:
boolean matches( )
It returnstrueif the sequence and the pattern match, andfalseotherwise. Understand that
the entire sequence must match the pattern, not just a subsequence of it.
To determine if a subsequence of the input sequence matches the pattern, usefind( ).
One version is shown here:
boolean find( )
It returnstrueif there is a matching subsequence andfalseotherwise. This method can be
called repeatedly, allowing it to find all matching subsequences. Each call tofind( )begins
where the previous one left off.
You can obtain a string containing the last matching sequence by callinggroup( ). One
of its forms is shown here:
String group( )
The matching string is returned. If no match exists, then anIllegalStateExceptionis thrown.
You can obtain the index within the input sequence of the current match by calling
start( ). The index one past the end of the current match is obtained by callingend( ). These
methods are shown here:
int start( )
int end( )
Both throwIllegalStateExceptionif no match exists.
You can replace all occurrences of a matching sequence with another sequence by
callingreplaceAll( ), shown here:
String replaceAll(StringnewStr)