Java Reference
In-Depth Information
Again, it checks if there was a previous match. Since this was the second call to the
find()
method, it will find a
previous match and it will use the append position saved by the last
appendReplacement()
call as the starting position.
The last character to be appended will be the character just before the second match. It will also set the append
position to the character position following the number 100. At this point, the
StringBuffer
contains the following text:
"A train carrying more than a hundred men and women was traveling at the speed of a hundred"
When you call the
find()
method for the third time, it will find the number 75 and the
StringBuffer
buffer
content will be as follows after the replacement. The append position will be set to the character position following
the number
75
.
"A train carrying more than a hundred men and women was traveling at the speed of a hundred miles
per hour. The train fare was less than a hundred"
If you call the
find(
) method again, it will not find any match. However, the
StringBuffer
does not contain the
text following the last match, which is “
dollars per person
.” To append the text following the last match, you need to
call the
appendTail()
method. It appends the text to the
StringBuffer
starting at append position until the end of the
input string. The call to this method
m.appendTail(sb);
will modify the
StringBuffer
to
"A train carrying more than a hundred men and women was traveling
at the speed of a hundred miles per hour. The train fare was less than
a hundred dollars per person."
What will the content of the
StringBuffer be
if you would have called the
appendTail()
method just after the
second call to the
appendReplacement()
method? The complete program is shown in Listing 14-7.
Listing 14-7.
Find-and-Replace Using Regular Expressions and appendReplacement() and appendTail() Methods
// AdvancedFindReplace.java
package com.jdojo.regex;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class AdvancedFindReplace {
public static void main (String[] args) {
String regex = "\\b\\d+\\b";
StringBuffer sb = new StringBuffer();
String replacementText = "";
String matchedText = "";
String text = "A train carrying 125 men and women was traveling at" +
" the speed of 100 miles per hour. " +
"The train fare was 75 dollars per person." ;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while (m.find()) {
matchedText = m.group();