To generate a replacement sequence of ab, the
Matcher matcher = pattern.matcher (”Thanks, thanks very much”); StringBuffer sb = new StringBuffer(); while (matcher.find()) { if (matcher.group(1).equals (”T”)) { matcher.appendReplacement (sb, “Thank you”); } else { matcher.appendReplacement (sb, “thank you”); } } matcher.appendTail (sb); Table 5-5 shows the sequence of changes applied to the StringBuffer by the above code. Table 5-5. Using appendReplacement() and appendTail() Append position Execute Resulting StringBuffer 0 appendReplacement (sb, “Thankyou”) Thank you 6 appendReplacement (sb, “thankyou”) Thank you, thank you 14 appendTail (sb) Thank you, thank youvery much This sequence of append operations results in the StringBuffer object sb containing the string “Thank you, thank you very much”. Example 5-8 is a complete code example showing this type of replacement, as well as alternate ways of performing the same substitution. In this simple case, the value of a capture group can be used because the first letter of the matched pattern is the same as that of the replacement. In a more complex case, there may not be an overlap between the input and the replacement values. Using Matcher.find() and Matcher.appendReplacement() allows you to programmatically mediate each replacement, possibly injecting different replacement values at each point along the way. Example 5-8. Regular expression append/replace package com.ronsoft.books.nio.regex; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Test the appendReplacement() and appendTail() methods of the * java.util.regex.Matcher class. * * @author Ron Hitchens (ron@ronsoft.com) */ public class RegexAppend{ 184
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services