Java 中沒有直接的字串減法運算子,但利用 String.replaceAll(String regex, String replacement) 即可輕鬆實現「移除指定子串」的效果:
String str1 = "abcd";
String str2 = "cd";
String str3 = str1.replaceAll(str2, "");
// 結果:str3 = "ab"
replaceAll 的第一個參數 是正則表達式,而非純字串。若 `str2` 包含正則特殊字元 (如 `.`, `*`, `?`, `+`, `[`, `]`, `(`, `)`, `{`, `}`, `|`, `^`, `$`, `\`),會導致非預期結果或拋出 `PatternSyntaxException`。
// 使用 Pattern.quote 自動轉義所有特殊字元,視為字面量
String str3 = str1.replaceAll(Pattern.quote(str2), "");
`replaceAll` 會移除 所有 匹配的子串,而非僅第一次出現:
String s = "ababab";
s.replaceAll("ab", ""); // 結果:"" (空字串),三個 "ab" 全被移除
// replaceFirst 僅替換首個匹配
String s = "ababab";
s.replaceFirst("ab", ""); // 結果:"abab"
若確定不需正則,使用 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。