String的replaceAll方法源码

import java.util.regex.Pattern;

/**
 * @author hspcadmin
 * @date 2021-10-21
 *
 */
public class MainApp {

    // 正则表达式
    protected static final String REGEX = "\bcat\b";

    public static void main(String[] args) {

        // 源字符串
        String params = "cat cat cat cattie cat";

        /**
         * 关键字替换 1. 正则表达式匹配关键字 2. 搜索到的关键字替换成指定字符
         */
        String replace = toReplaceAll(params, REGEX, "|");
        System.out.println("replaceAll = " + replace);

        // String类的replaceAll方法 源码支持正则表达式匹配关键字 然后替换
        String replaceAll1 = params.replaceAll(REGEX, "|");
        System.out.println("replaceAll1 = " + replaceAll1);
    }

    private static String toReplaceAll(String resource, String regex, String replacement) {
        return Pattern.compile(regex).matcher(resource).replaceAll(replacement);
    }
}


-------------------------------------------------------------------------------------------------------------------------------------------------
// 源码
public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
原文地址:https://www.cnblogs.com/w1440199392/p/15433812.html