共計 574 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,replaceAll() 方法是用來替換字符串中的匹配項。它接受兩個參數:第一個參數是一個正則表達式,用于指定匹配的模式;第二個參數是一個替換字符串,用于指定替換后的內容。
使用示例:
- 替換字符串中的所有匹配項:
String str = "Hello, World!";
String replacedStr = str.replaceAll("o", "a");
System.out.println(replacedStr); // 輸出:Hella, Warld!
- 替換字符串中的多個匹配項:
String str = "Hello, World!";
String replacedStr = str.replaceAll("[l,o]", "a");
System.out.println(replacedStr); // 輸出:Heaao, Warad!
- 忽略大小寫替換:
String str = "Hello, World!";
String replacedStr = str.replaceAll("(?i)o", "a");
System.out.println(replacedStr); // 輸出:Hella, Warld!
請注意,replaceAll() 方法返回一個新的字符串,原始字符串并沒有改變。如果要在原始字符串上進行替換,可以使用 replace() 方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完