replaceAll("\\.", File.separator)报错
错误:
StringIndexOutOfBoundsException:String index out of range: -1;
遇到一个很怪的问题:
1 | String packagePath = packageName.replaceAll( “\.” , File.separator); |
貌似上面代码没有问题,但运行是会报StringIndexOutOfBoundsException的错误。
查看文档:documentation
1 | 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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string. |
得知,在使用replaceAll时,如果替换的字符中包含’\‘或者’$’符号可能会导致意想不到的结果。因为替换时使用了正则表达式,而’\‘和’$’是正则中的关键字,替换会造成混淆。
解决办法:使用Matcher.quoteReplacement(sep)转义。
1 | packageDecl = packageDecl.replaceAll( “\.” , Matcher.quoteReplacement(File.separator)); |
还没有评论,来说两句吧...