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.
You can simply do it with
String#replace(): –String#replaceAlltakes aregexas parameter. So, you would have to escape thebackslashtwice. Once forJavaand then forRegex. So, the actual replacement usingreplaceAllwould look like: –But you don’t really need a
replaceAllhere.