欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-02 13:49:55
...

在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