replaceAll() 方法

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为原字符串
原文地址:https://www.cnblogs.com/StriveE2/p/9134396.html