扫码一下
查看教程更方便
Regex类 appendReplacement() 方法实现了非终端追加和替换步骤。
public Matcher appendReplacement(StringBuffer sb, String replacement)
这个匹配器。
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-