"\\\\". replaceAll ("\\\\", "\\") throws java.lang.StringIndexOutOfBoundsException

The following code snippet in Java:

"\\\\".replaceAll("\\\\", "\\");

throws an exception:

java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (NO_SOURCE_FILE:0)

javadoc on replaceAll includes a caution about using backslashes and recommends using Matcher.replaceAll or Matcher.quoteReplacement . Does anyone have a snippet of how to replace all occurrences of two backslashes in a string with one backslash?

lightening

The actual literal shown above is just an example; in fact, a string can have many occurrences of two consecutive backslashes in different places.

+5
source share
4

String#replace(): -

"\\\\".replace("\\\\", "\\")

String#replaceAll regex as. , backslash . Java, regex. , replaceAll : -

"\\\\".replaceAll("\\\\\\\\", "\\\\")

replaceAll.

+10

:

"\\\\".replaceAll("\\{2}", "\\")

replaceAll() , {2} , char.

+1

Matcher.replaeAll(), - :

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

, escape, . StringIndexOutOfBoundsException.

0

All Articles