Java Reference
In-Depth Information
appendTail(StringBuffer)
Appends text after the last match (normally used after appendReplacement ).
Example 4-3 shows use of these three methods.
Example 4-3. ReplaceDemo.java
/**
* Quick demo of RE substitution: correct U.S. 'favor'
* to Canadian/British 'favour', but not in "favorite"
* @author Ian F. Darwin, http://www.darwinsys.com/
*/
public
public class
class ReplaceDemo
ReplaceDemo {
public
public static
static void
void main ( String [] argv ) {
// Make an RE pattern to match as a word only (\b=word boundary)
String patt = "\\bfavor\\b" ;
// A test input.
String input = "Do me a favor? Fetch my favorite." ;
System . out . println ( "Input: " + input );
// Run it from a RE instance and see that it works
Pattern r = Pattern . compile ( patt );
Matcher m = r . matcher ( input );
System . out . println ( "ReplaceAll: " + m . replaceAll ( "favour" ));
// Show the appendReplacement method
m . reset ();
StringBuffer sb = new
new StringBuffer ();
System . out . print ( "Append methods: " );
while
while ( m . find ()) {
// Copy to before first match,
// plus the word "favor"
m . appendReplacement ( sb , "favour" );
}
m . appendTail ( sb ); // copy remainder
System . out . println ( sb . toString ());
}
}
Sure enough, when you run it, it does what we expect:
Search WWH ::




Custom Search