7

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

4 Answers4

13

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

If you want to use Matcher.replaeAll() then you want something like this:

Pattern.compile("\\\\\\\\").matcher(input).replaceAll("\\\\");
0

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.

Renjith
  • 3,274
  • 19
  • 39