问题
The following code fragment in Java:
"\\\\".replaceAll("\\\\", "\\");
throws the exception:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (NO_SOURCE_FILE:0)
The javadoc on replaceAll does include a caveat on the use of backslashes and recommends using Matcher.replaceAll or Matcher.quoteReplacement. Does anybody have a snippet on how to replace all occurrences of two backslashes in a string with a single backslash ?
clarification
The actual literal shown above is only an example, the actually string can have many occurrences of two consecutive backslashes in different places.
回答1:
You can simply do it with String#replace(): -
"\\\\".replace("\\\\", "\\")
String#replaceAll takes a regex
as parameter. So, you would have to escape the backslash
twice. Once for Java
and then for Regex
. So, the actual replacement using replaceAll
would look like: -
"\\\\".replaceAll("\\\\\\\\", "\\\\")
But you don't really need a replaceAll
here.
回答2:
Try this instead:
"\\\\".replaceAll("\\{2}", "\\")
The first parameter to replaceAll()
is a regular expression, and {2}
indicates that exactly two occurrences of the char must be matched.
回答3:
If you want to use Matcher.replaeAll()
then you want something like this:
Pattern.compile("\\\\\\\\").matcher(input).replaceAll("\\\\");
回答4:
If you have backslash in replacement string, it will be treated as escape character and the method will try to read the next character.That is why , it is throwing StringIndexOutOfBoundsException.
来源:https://stackoverflow.com/questions/14650064/replaceall-throws-java-lang-stringindexoutofboundsexception