今天在项目中使用java中replace方法将字符串中的反斜杠("")替换成空字符串(""),
结果出现如下的异常:
java.util.regex.PatternSyntaxException: Unexpected internal error near index
错误的原因:在regex中"\"表示一个"",在java中一个""也要用"\"表示。这样,前一个"\"代表regex中的"",后一个"\"代表java中的""。所以要想使用replace方法将字符串中的反斜杠("")替换成空字符串(""),则需要这样写:str.replace("\\","");
例如:
String testReplace="usr\local\host";
testReplace.replaceAll("\","");
执行代码会报错:java.util.regex.PatternSyntaxException: Unexpected internal error near index
正确的写法是:
testReplace.replaceAll("\\","");