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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值