words, the substring defined by start and end.
public intgroupCount()
Returns the number of capturing groups in this matcher's pattern. Group
numbers range from zero to one less than this count.
public Stringgroup(int group)
Returns the input subsequence matched by the given group in the previous
match. Group zero is the entire matched pattern, so group(0) is equivalent
to group().
public intstart(int group)
Returns the start index of the given group from the previous match.
public intend(int group)
Returns the index of the last character matched of the given group, plus one.
Together these methods form the MatchResult interface, which allows a match result to be queried but not
modified. You can convert the current matcher state to a MatchResult instance by invoking its
toMatchResult method. Any subsequent changes to the matcher state do not affect the existing
MatchResult objects.
13.3.3. Replacing
You will often want to pair finding matches with replacing the matched characters with new ones. For
example, if you want to replace all instances of sun with moon, your code might look like this:[2]
[2] The StringBuffer class (see page 335) is an appendable character sequence (you can
modify its contents). The Matcher class should have been updated in the 5.0 release to work
with any appendable character sequence, such as StringBuilder, but this was
overlooked.
Pattern pat = Pattern.compile("sun");
Matcher matcher = pat.matcher(input);
StringBuffer result = new StringBuffer();
boolean found;
while ((found = matcher.find()))
matcher.appendReplacement(result, "moon");
matcher.appendTail(result);
The loop continues as long as there are matches to sun. On each iteration through the loop, all the characters
from the append position (the position after the last match; initially zero) to the start of the current match are
copied into the string buffer. Then the replacement string moon is copied. When there are no more matches,
appendTail copies any remaining characters into the buffer.
The replacement methods of Matcher are
public StringreplaceFirst(String replacement)