首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 字串「減法」最簡單實現:replaceAll 移除指定子串

     編輯:Java 程式設計入門

核心方案

Java 中沒有直接的字串減法運算子,但利用 String.replaceAll(String regex, String replacement) 即可輕鬆實現「移除指定子串」的效果:

String str1 = "abcd";
String str2 = "cd";
String str3 = str1.replaceAll(str2, "");
// 結果:str3 = "ab"

關鍵注意事項

1. 參數是正則表達式

replaceAll 的第一個參數 是正則表達式,而非純字串。若 `str2` 包含正則特殊字元 (如 `.`, `*`, `?`, `+`, `[`, `]`, `(`, `)`, `{`, `}`, `|`, `^`, `$`, `\`),會導致非預期結果或拋出 `PatternSyntaxException`。

安全寫法:轉義特殊字元

// 使用 Pattern.quote 自動轉義所有特殊字元,視為字面量
String str3 = str1.replaceAll(Pattern.quote(str2), "");

2. 移除所有匹配項

`replaceAll` 會移除 所有 匹配的子串,而非僅第一次出現:

String s = "ababab";
s.replaceAll("ab", ""); // 結果:"" (空字串),三個 "ab" 全被移除

3. 若需僅移除第一次出現

// replaceFirst 僅替換首個匹配
String s = "ababab";
s.replaceFirst("ab", ""); // 結果:"abab"

4. 純字串替換 (非正則) 效能更好

若確定不需正則,使用 replace(CharSequence target, CharSequence replacement) (無正則解析開銷):

String str3 = str1.replace(str2, ""); // 內部不使用正則引擎,效能略優

效能對比建議

方法是否正則適用場景效能
replaceAll(regex, "")是需正則匹配 (如移除所有數字 \\d)較慢 (編譯 Pattern)
replace(target, "")否固定字串移除/替換快 (字面量匹配)
replaceFirst(regex, "")是僅移除首個匹配中等

完整範例:安全的字串減法工具方法

import java.util.regex.Pattern;

public class StringUtils {
    /**
     * 字串減法:從 source 中移除所有 target 子串 (字面量匹配,非正則)
     * @param source 原字串
     * @param target 要移除的子串
     * @return 移除後的字串,若 source 為 null 則返回 null
     */
    public static String subtract(String source, String target) {
        if (source == null || target == null || target.isEmpty()) {
            return source;
        }
        // 使用 Pattern.quote 確保 target 被視為字面量
        return source.replaceAll(Pattern.quote(target), "");
    }
    
    // 測試
    public static void main(String[] args) {
        System.out.println(subtract("abcd", "cd"));        // ab
        System.out.println(subtract("a.b.c", "."));        // abc (而非正則匹配任意字元)
        System.out.println(subtract("hello world", " "));  // helloworld
        System.out.println(subtract("test", "x"));         // test (不存在無影響)
        System.out.println(subtract(null, "a"));           // null
    }
}

總結

Java 字串「減法」首選 replace(target, "") (固定字串) 或 replaceAll(Pattern.quote(target), "") (含特殊字元)。切記 replaceAll 參數是正則,**務必用 Pattern.quote 轉義** 以避免坑。效能敏感場景優先用 replace。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved