集册 Java实例教程 正则表达式匹配后替换

正则表达式匹配后替换

欢马劈雪     最近更新时间:2020-01-02 10:19:05

408
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
正则表达式匹配后替换
/*来自 
 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());

    }

}


展开阅读全文