Java正则替换
private static String REGEX ="a*b"; private static String INPUT ="aabfooaabfooaabfooaabfooaabfooaabfoo"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); StringBuffer sb = new StringBuffer(); //循环替换 while(m.find()) m.appendReplacement(sb, REPLACE); //添加尾部字符串 m.appendTail(sb); System.out.println(sb.toString()); }
修改成如此也可以:
private static String REGEX ="a*b"; private static String INPUT ="aabfooaabfooaabfooaabfooaabfooaabfoo"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); //StringBuffer sb = new StringBuffer(); //循环替换 //while(m.find()) // m.appendReplacement(sb, REPLACE); //添加尾部字符串 //m.appendTail(sb); System.out.println(INPUT); }
结果: