Java Reference
In-Depth Information
Start using the
find()
method on the
Matcher
object to find a match. When you invoke the
find()
method for
the first time, the number 125 will match the pattern. At this point, you would like to prepare the replacement text
depending on the matched text as:
String replacementText = "";
// Get the matched text. Recall that group() method returns the whole matched text
String matchedText = m.group();
// Convert the text into integer for comparison
int num = Integer.parseInt(matchedText);
// Prepare the replacement text
if (num == 100) {
replacementText = "a hundred";
}
else if (num < 100) {
replacementText = "less than a hundred";
}
else {
replacementText = "more than a hundred";
}
Now, you will call the
appendReplacement()
method on the
Matcher
object, passing an empty
StringBuffer
and
replacementText
as arguments. In this case,
replacementText
has a string
"more than hundred"
because the
find()
method call matched the number 125.
m.appendReplacement(sb, replacementText);
It is interesting to know what the
appendReplacement()
method call does. It checks if there was a previous match.
Because this is the first call to the
find()
method, there is no previous match. For the first match, it appends the text
starting from the beginning of the input text until the character before the matching text. In your case, the following
text is appended to the StringBuffer. At this point, the text in the StringBuffer is
"A train carrying "
Now the
appendReplacement()
method appends the text in the
replacementText
argument to the
StringBuffer
.
This will change the
StringBuffer
contents to
"A train carrying more than a hundred"
The
appendReplacement()
method does one more thing. It sets the append position (an internal state of the
Matcher
object) to the character position just after the first matching text. In your case, the append position will be set
to the character following 125, which is the position of the space character that follows 125. This finishes the first find
and replace step.
You will call the
find()
method of the
Matcher
object again. It will find the pattern, that is, another number, which
is 100. You will compute the value of the replacement text using the same procedure as you did after the first match.
This time, the
replacementText
will contain the string
"a hundred"
. You call
appendReplacement()
method as follows:
m.appendReplacement(sb, replacementText);