提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
正则表达式匹配后替换
/*来自 n o w j a v a . c o m - 时代Java*/ import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexDemo { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, REPLACE);/*时代Java公众号 提 供*/ } m.appendTail(sb); System.out.println(sb.toString()); } }