java 当我尝试用 `\` 替换 `\\` 时,为什么会出现 StringIndexOutOfBoundsException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1049103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting a StringIndexOutOfBoundsException when I try to replace `\\` with `\`?
提问by Rakesh Juyal
I have to replace \\with \in Java. The code I am using is
我必须\\用\Java替换。我使用的代码是
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\", "\") );
But I don't know why it is throwing StringIndexOutOfBoundsException.
但我不知道它为什么会抛出StringIndexOutOfBoundsException.
It says String index out of range: 1
它说 String index out of range: 1
What could be the reason? I guess it is because the first argument replaceAllaccepts a pattern. What could be the possible solution?
可能是什么原因?我想这是因为第一个参数replaceAll接受一个模式。可能的解决方案是什么?
Stacktrace
堆栈跟踪
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:558)
at java.util.regex.Matcher.appendReplacement(Matcher.java:696)
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)
Answer Found
找到答案
asalamon74posted the code I required, but I don't know why he deleted it. In any case here it is.
asalamon74贴了我需要的代码,但我不知道他为什么删除了它。无论如何,它在这里。
There is a bugalready filed in Java's bug database. (Thanks for this reference, asalamon.)
Java 的错误数据库中已经存在一个错误。(感谢这个参考,asalamon。)
yourString.replaceAll("\\", "\\");
Amazingly, both search and replace string are the same :) but still it does what I require.
令人惊讶的是,搜索和替换字符串都是相同的 :) 但它仍然满足我的要求。
回答by Jon Skeet
Use String.replaceinstead of replaceAllto avoid it using a regex:
使用String.replace而不是replaceAll使用正则表达式来避免它:
String original = MyConstants.LOCATION_PATH + File.seperator
+ myObject.getStLocation();
System.out.println(original.replace("\\", "\"));
Personally I wouldn't do it this way though - I'd create MyConstants.LOCATION_PATH_FILE as a Fileand then you could write:
我个人不会这样做 - 我会创建 MyConstants.LOCATION_PATH_FILE 作为 aFile然后你可以写:
File location = new File(MyConstants.LOCATION_PATH_FILE,
myObject.getStLocation());
which will do the right thing automatically.
这将自动做正确的事情。
回答by user85421
Well, i tried
嗯,我试过了
String test = "just a \ test with some \\ and others \\ or \ so";
String result = test.replaceAll("\\", "\\");
System.out.println(test);
System.out.println(result);
System.out.println(test.equals(result));
and got, as expected
并得到了,正如预期的那样
just a \ test with some \ and others \ or \ so
just a \ test with some \ and others \ or \ so
true
What you really needis
你真正需要的是
string.replaceAll("\\\\", "\\");
to get
要得到
just a \ test with some \ and others \ or \ so
just a \ test with some \ and others \ or \ so
false
You want to find: \\??(2 slashes)
which needs to be escaped in the regex: \\\\(4 slashes)
and escaped in Java: "\\\\\\\\"(8 slashes)
same for the replacement...
您想找到:\\??(2 slashes)
需要在正则表达式中转义:\\\\(4 条斜线)
并在 Java 中转义:"\\\\\\\\"(8 条斜线)
与替换相同...
回答by Shree ram
For the regex, if you want to change \to \\, you should do this:
对于正则表达式,如果要更改\为\\,则应执行以下操作:
if (str.indexOf('\') > -1)
str = str.replaceAll("\\", "\\\\");
str = "\"" + str + "\"";
Where \\\\means \and \\\\\\\\means \\.
其中\\\\的手段\和\\\\\\\\方法\\。
回答by Thomas Neveu
The best way is :
最好的方法是:
str.replace(**'**\**'**, **'**/**'**); //with char method not String
回答by stevehipwell
File.seperator is already escaped as is any string object so you are escaping them twice.
File.seperator 已经像任何字符串对象一样被转义,所以你要转义它们两次。
You only need to escape values that you are entering as a string literal.
您只需要转义您作为字符串文字输入的值。
回答by Diego Santillan
Try this
试试这个
cadena.replaceAll("\\","\\\\")
回答by Michael Borgwardt
I suspect the problem is that replaceAll()uses regexps and the backslash is an escape character in regexps as well as in Java - it might be necessary to double the number of backslashes.
我怀疑问题在于replaceAll()使用正则表达式并且反斜杠是正则表达式和 Java 中的转义字符 - 可能需要将反斜杠的数量加倍。
In general you should always post the full stack trace of exceptions, it is much easier to diagnose the problem that way.
通常,您应该始终发布异常的完整堆栈跟踪,这样更容易诊断问题。
回答by Hyman Leow
I believe what you need to do is:
我相信你需要做的是:
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\", "\\") );
The regular expression String is actually four backslashes, which is a regular expression that matches two backslashes.
正则表达式String其实就是四个反斜杠,就是匹配两个反斜杠的正则表达式。
The replacement String has to be four slashes as per Java documentation, from: http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)
根据 Java 文档,替换字符串必须是四个斜杠,来自:http: //java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String )
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.
请注意,替换字符串中的反斜杠 () 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同。美元符号可以被视为对上述捕获子序列的引用,反斜杠用于转义替换字符串中的文字字符。
回答by Ujjwal
final StringBuilder result = new StringBuilder();
final StringCharacterIterator iterator = new StringCharacterIterator(str);
char character = iterator.current();
while (character != CharacterIterator.DONE )
{
if (character == '\\') {
result.append("\");
}
else {
result.append(character);
}
character = iterator.next();
}
System.out.print(result);

