replaceAll()方法实际是采用正则表达式的规则去匹配的。
replaceAll中一个“\”要用“\\\\”来表示。
在regex中“\\”表示一个“\”,正则转义一次,在java中一个“\”也要用"\\"表示,即字符串转义一次,所以写成“\\\\”。
想要将字符串路径中的反斜杠转为正斜杠,应写成replaceAll("/", “\\\\”);
此外,有时候我们需要把路径中的斜杠用File.separator来替换。如果写成replaceAll("\\", File.separator)
会出现错误:
java.lang.IllegalArgumentException: character to be escaped is missing-1;
这是因为,“\”和“$”是正则中的关键字,在使用replaceAll时,如果替换的字符中包含“\”或者“$”符号,替换会混淆。
解决办法:使用Matcher.quoteReplacement(sep)转义。
str=str.replaceAll("xxxx",Matcher.quoteReplacement(File.separator));