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);
    }

 

结果:

 

 感谢:https://www.icourse163.org/learn/ECNU-1003718005?tid=1003949006#/learn/content?type=detail&id=1210288147&cid=1212239443&replay=true

posted @ 2020-09-14 14:37  蜗牛的礼物  阅读(788)  评论(0编辑  收藏  举报