我正在尝试以下代码: –
String x = "asdfg/dgws"; x.replaceAll("/","\\");
但这是失败的.这给了我以下错误信息: –
Exception in thread "main" java.lang.Stringindexoutofboundsexception: String index out of range: 1 at java.lang.String.charat(UnkNown Source) at java.util.regex.Matcher.appendReplacement(UnkNown Source) at java.util.regex.Matcher.replaceAll(UnkNown Source) at java.lang.String.replaceAll(UnkNown Source) at com.jai.SecLargest.main(SecLargest.java:13)
我无法弄清楚为什么会出现这种异常?
解决方法
String.replaceAll最终使用(或等同于使用)
Matcher.replaceAll
,其中包含以下内容:
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.
虽然您可以根据AlexR的答案逃避反斜杠,但我强烈建议您使用替换:
String y = x.replace('/','\\');
这更清楚,IMO – 除非你真的试图通过正则表达式来表达模式,否则不要使用replaceAll.
另请注意,编写代码时无论如何都是无操作的;字符串在Java中是不可变的,因此replaceAll方法(以及类似的方法)返回对带有修改的新字符串的引用.