Java Reference
In-Depth Information
The
find()
method will return
true
three times, once for each occurrence of "
dog
" in
joke
. When
the three steps shown in the diagram have been completed, the
find()
method returns
false
on the
next loop iteration, terminating the loop. This leaves
newJoke
in the state shown in the last box above.
All we now need to complete
newJoke
is a way to copy the text from
joke
that comes after the last
subsequence that was found. The
appendTail()
method for the
Matcher
object does that:
m.appendTail(newJoke);
This will copy the text starting with the
m.end()
index position from the last successful match through
to the end of the string. Thus this statement copies the segment "
smells horrible.
" from
joke
to
newJoke
. We can put all that together and run it.
Try It Out - Search and Replace
Here's the code we have just discussed assembled into a complete program:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class SearchAndReplace {
public static void main(String args[]) {
String joke = "My dog hasn't got any nose.\n"
+"How does your dog smell then?\n"
+"My dog smells horrible.\n";
String regEx = "dog";
Pattern doggone = Pattern.compile(regEx);
Matcher m = doggone.matcher(joke);
StringBuffer newJoke = new StringBuffer();
while(m.find())
m.appendReplacement(newJoke, "goat");
m.appendTail(newJoke);
System.out.println(newJoke.toString());
}
}
When you compile and execute this you should get the output:
My goat hasn't got any nose.
How does your goat smell then?
My goat smells horrible.
How It Works
Each time the
find()
method returns
true
in the
while
loop condition, we call the
appendReplacement()
method for the
Matcher
object,
m
. This copies characters from
joke
to
newJoke
, starting with the index position where the
find()
method started searching, and ending at
the character preceding the first character in the match, which will be at
m.start()-1
. The method
then appends the replacement string, "
goat
", to the contents of
newJoke
. Once the loop finishes, the
appendTail()
method copies characters from
joke
to
newJoke
, starting with the character
following the last match at
m.end()
, through to the end of
joke
. Thus we end up with a new string
similar to the original, but which has each instance of "
dog
" replaced by "
goat
".