replaceAll() 方法的簡單使用
replaceAll() 方法使用給定的參數 replacement 替換字符串所有匹配給定的正則表達式的子字符串。
語法
public String replaceAll(String regex, String replacement)
參數
- regex -- 匹配此字符串的正則表達式。
- newChar -- 用來替換每個匹配項的字符串。
返回值
成功則返回替換的字符串,失敗則返回原始字符串。
實例
1 public class Test { 2 public static void main(String args[]) { 3 String Str = new String("www.google.com"); 4 5 System.out.print("匹配成功返回值 :" ); 6 System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" )); 7 System.out.print("匹配失敗返回值 :" ); 8 System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" )); 9 } 10 }
以上程序執行結果為:
匹配成功返回值 :runoob 匹配失敗返回值 :
www.google.com
用法二
更換單獨字符
1 String last = modified.replaceAll("a" ,"A").replaceAll("e", "E").replaceAll("i", "I").replaceAll("o","O").replaceAll("u", "U"); 2 // modified為原字符串