Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 634
Marcus Junius Brutus Avatar asked Feb 01 '13 15:02

Marcus Junius Brutus


People also ask

How do I fix Java Lang StringIndexOutOfBoundsException?

The StringIndexOutOfBoundsException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps: Surround the statements that can throw an StringIndexOutOfBoundsException in try-catch blocks. Catch the StringIndexOutOfBoundsException.

What is Java Lang StringIndexOutOfBoundsException?

Class StringIndexOutOfBoundsExceptionThrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

How do you fix a string index out of range 1?

This error is raised when the string index you are trying to access or operate is out of the range you are mentioning in your code. The way to fix this error is to mention the correct index of the desired element of operation. You can also see if there are indentation mistakes in your code that can also be then reason.

How do I fix string 0 out of range?

To resolve the problem, simply remove any offending instances of unnecessary letters/symbols or words which do not belong in the mappings file.


2 Answers

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.

like image 109
Rohit Jain Avatar answered Oct 18 '22 02:10

Rohit Jain


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.

like image 1
Óscar López Avatar answered Oct 18 '22 02:10

Óscar López