扫码一下
查看教程更方便
Regex类 appendTail(StringBuffer sb)方法实现了一个终端追加和替换步骤。
public Matcher appendTail(StringBuffer sb)
目标字符串缓冲区。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherDemo { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); StringBuffer buffer = new StringBuffer(); while(matcher.find()) { matcher.appendReplacement(buffer, REPLACE); } matcher.appendTail(buffer); System.out.println(buffer.toString()); } }
上面示例编译运行结果如下
-foo-foo-foo-