Java replace和replaceAll 区别

it2022-05-05  62

1   String src = new String("ab43a2c43d"); 2   System.out.println(src.replace("3","f"));=>ab4f2c4fd. 3   System.out.println(src.replace('3','f'));=>ab4f2c4fd. 4   System.out.println(src.replaceAll("\\d","f"));=>abffafcffd. 5   System.out.println(src.replaceAll("a","f"));=>fb43fc23d. 6   System.out.println(src.replaceFirst("\\d,"f"));=>abf32c43d 7   System.out.println(src.replaceFirst("4","h"));=>abh32c43d. 8   如何将字符串中的"\"替换成"\\": 9   String msgIn; 10   String msgOut; 11   msgOut=msgIn.replaceAll("\\\\","\\\\\\\\"); 12   原因: 13   '\'在java中是一个转义字符,所以需要用两个代表一个。例如System.out.println( "\\" ) ;只打印出一个"\"。但是'\'也是正则表达式中的转义字符(replaceAll 的参数就是正则表达式),需要用两个代表一个。所以:\\\\被java转换成\\,\\又被正则表达式转换成\。 14   同样 15   CODE: \\\\\\\\ 16   Java: \\\\ 17   Regex: \\ 18   将字符串中的'/'替换成'\'的几种方式: 19   msgOut= msgIn.replaceAll("/", "\\\\"); 20   msgOut= msgIn.replace("/", "\\"); 21   msgOut= msgIn.replace('/', '\\');

 

转载于:https://www.cnblogs.com/tiantao201101/p/5355752.html


最新回复(0)