String的replaceAll方法原始碼
阿新 • • 發佈:2021-10-21
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); }