separator在执行replaceAll时异常的解决办法

在java中,为了保证跨平台时目录可以正确被访问,我们会使用到File.separator来获取当前系统的目录分隔符。

但是如果使用replaceAll替换这个分隔符会出现下边的异常。

path = path.replaceAll(File.separator,"-");
=====================================
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1

我们来看一下replaceAll的API描述

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement to suppress the special meaning of these characters, if desired.

 注意:”\“和"$"在做为替换字符串的时候,可能会出现一个不同的结果,建议我们使用Matcher.quoteReplacement函数先对替换字符进行转译。

System.out.println(File.separator); //输出 "\"
System.out.println(Matcher.quoteReplacement(File.separator));  //输出"\\"
System.out.println("/"); //输出 "/"
System.out.println(Matcher.quoteReplacement("/")); //输出 "/"
System.out.println("$"); //输出 "/" 
System.out.println(Matcher.quoteReplacement("$")); //输出 "/"

上边的语句应该修改为:

path = path.replaceAll(Matcher.quoteReplacement(File.separator),"-");

最后来看看Matcher.quoteReplacement(sep)的API说明。

java.util.regex.Matcher
public static java.lang.String quoteReplacement(java.lang.String s)
Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.
Parameters:
s - The string to be literalized
Returns:
A literal string replacement
Since:
1.5

 

你可能感兴趣的:(java)