Java String replace()
replace() 方法用來取代字串中的字元或子字串。
語法
// 取代字元
string.replace(char oldChar, char newChar)
// 取代字串
string.replace(CharSequence target, CharSequence replacement)
// 使用正規表達式取代
string.replaceAll(String regex, String replacement)
string.replaceFirst(String regex, String replacement)
replace() 範例
取代字元
String s = "Hello World";
String result = s.replace('o', '0');
System.out.println(result); // "Hell0 W0rld"
String result2 = s.replace('l', 'L');
System.out.println(result2); // "HeLLo WorLd"
取代字串
String s = "Hello World";
String result = s.replace("World", "Java");
System.out.println(result); // "Hello Java"
String result2 = s.replace("l", "L");
System.out.println(result2); // "HeLLo WorLd"
replaceAll()
使用正規表達式取代所有符合的部分:
String s = "Hello123World456";
// 取代所有數字
String result = s.replaceAll("\\d", "");
System.out.println(result); // "HelloWorld"
// 取代所有數字(一次取代連續數字)
String result2 = s.replaceAll("\\d+", "#");
System.out.println(result2); // "Hello#World#"
// 移除多餘空白
String s2 = "Hello World";
String result3 = s2.replaceAll("\\s+", " ");
System.out.println(result3); // "Hello World"
replaceFirst()
只取代第一個符合的部分:
String s = "apple apple apple";
String result = s.replaceFirst("apple", "orange");
System.out.println(result); // "orange apple apple"
replace vs replaceAll
| 方法 | 參數 | 用途 |
|---|---|---|
replace() | 字串 | 簡單的文字取代 |
replaceAll() | 正規表達式 | 複雜的模式取代 |
String s = "a.b.c";
// replace() 會當作普通字串
String r1 = s.replace(".", "-");
System.out.println(r1); // "a-b-c"
// replaceAll() 的 . 是正規表達式(匹配任意字元)
String r2 = s.replaceAll(".", "-");
System.out.println(r2); // "-----"
// replaceAll() 需要跳脫特殊字元
String r3 = s.replaceAll("\\.", "-");
System.out.println(r3); // "a-b-c"
實際應用
移除特定字元
String phone = "(02) 1234-5678";
// 只保留數字
String digits = phone.replaceAll("[^0-9]", "");
System.out.println(digits); // "0212345678"
遮蔽敏感資訊
String creditCard = "1234-5678-9012-3456";
String masked = creditCard.substring(0, 14).replace(creditCard.substring(0, 14), "****-****-****") + creditCard.substring(14);
// 更簡單的方式
String masked2 = creditCard.replaceAll("\\d(?=\\d{4})", "*");
System.out.println(masked2); // "****-****-****-3456"
清理輸入
String input = " Hello World ";
// 去除前後空白,壓縮中間空白
String clean = input.trim().replaceAll("\\s+", " ");
System.out.println(clean); // "Hello World"
移除 HTML 標籤
String html = "<p>Hello <b>World</b></p>";
String text = html.replaceAll("<[^>]+>", "");
System.out.println(text); // "Hello World"
駝峰命名轉蛇形命名
String camelCase = "getUserName";
String snakeCase = camelCase.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
System.out.println(snakeCase); // "get_user_name"
注意事項
字串是不可變的,replace() 會回傳新字串:
String s = "Hello";
s.replace("H", "J"); // 沒有賦值,s 不會改變
System.out.println(s); // "Hello"
s = s.replace("H", "J"); // 需要賦值
System.out.println(s); // "Jello"