`
superxielei
  • 浏览: 262296 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

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

    博客分类:
  • java
阅读更多

在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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics