Java Reference
In-Depth Information
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 copies 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 .
You can put all that together and run it.
TRY IT OUT: Search and Replace
Here's the code I 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);
}
}
SearchAndReplace.java
When you compile and execute this you should get the following 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 in the while loop condition returns true , you call the appendReplace-
ment() method for the Matcher object m . This copies characters from joke to newJoke , starting at the
index position where find() started searching, and ending at the character preceding the first character
Search WWH ::




Custom Search