一、方法簡介
replaceAll方法是Java String類中的一個常用方法,用於將字元串中指定的字元或字元串替換為新的字元或字元串。
該方法的幾種重載形式:
public String replaceAll(String regex, String replacement) public String replaceAll(String regex, Function<MatchResult, String> replacer)
二、參數詳解
1. regex – 用於匹配要替換的子字元串的正則表達式字元串。
2. replacement – 替換掉匹配子串的字元串。
3. replacer – 一個接受匹配結果的處理器,返回替換後的字元串。
三、使用示例
1. 替換字元
下面的示例將原字元串中所有的字元’a’替換成字元’b’:
String str = "I like apples and bananas."; String newStr = str.replaceAll("a", "b"); System.out.println(newStr); // output: "I like bbpples bnd bbnnbbns."
2. 替換字元串
下面的示例將原字元串中所有的字元串”app”替換成字元串”orange”:
String str = "I like apples and bananas."; String newStr = str.replaceAll("app", "orange"); System.out.println(newStr); // output: "I like oranges and bananas."
3. 替換匹配的子串
下面的示例將原字元串中所有的數字替換成它們的平方:
String str = "1 2 3 4 5"; String newStr = str.replaceAll("\\d+", match -> { int num = Integer.parseInt(match.group()); return Integer.toString(num*num); }); System.out.println(newStr); // output: "1 4 9 16 25"
四、替換非ASCII字元
在替換包含非ASCII字元的字元串時,需要注意一些特殊情況,例如替換一個帶有重音符的字元:
String str = "r\u00E9sum\u00E9"; String newStr = str.replaceAll("\u00E9", "e"); System.out.println(newStr); // output: "resume"
注意,直接使用replaceAll替換字元串中的非ASCII字元可能會出現意想不到的結果。有時候我們需要使用Unicode編碼來進行替換。
替換所有非ASCII字元
下面的示例將字元串中所有的非ASCII字元替換成一個空白字元:
String str = "a1\u00E9\u00F2\u0020b2c"; String newStr = str.replaceAll("[^\\x00-\\x7F]", " "); System.out.println(newStr); // output: "a1 b2c"
總結
Java String類的replaceAll方法是一個非常有用的字元串替換工具,可以方便地實現各種字元串替換操作。在使用時需要注意參數的正確選擇以及處理特殊情況。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/206161.html