下面的代码演示了创建程序以查找和替换字符串中的子字符串的用法Matcher.appendReplacement()和Matcher.appendTail()方法。
在以下示例中可以找到另一种可用于搜索和替换字符串的解决方案:如何使用正则表达式创建字符串搜索和替换?
package org.nhooo.example.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AppendReplacementExample {
public static void main(String[] args) {
// 创建一个模式实例
Pattern pattern = Pattern.compile("[Pp]en");
// 创建匹配对象
String input = "Please use your Pen to answer the question, " +
"black pen is preferred.";
Matcher matcher = pattern.matcher(input);
StringBuffer sb = new StringBuffer();
// 查找并替换与模式匹配的文本
while (matcher.find()) {
matcher.appendReplacement(sb, "pencil");
}
// 此方法从输入序列读取字符,从
// 在附加位置,并将它们附加到给定的字符串
//缓冲。它打算在一个或多个之后调用
// 调用appendReplacement方法以进行复制
// 输入序列的其余部分。
matcher.appendTail(sb);
System.out.println("Input : " + input);
System.out.println("Output: " + sb.toString());
}
}这是上面代码的结果:
Input : Please use your Pen to answer the question, black pen is preferred. Output: Please use your pencil to answer the question, black pencil is preferred.