3

I am trying the following code:-

String x = "asdfg/dgws";
x.replaceAll("/", "\\");

But this is failing. This is giving me the following error message:-

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(Unknown Source)
    at java.util.regex.Matcher.appendReplacement(Unknown Source)
    at java.util.regex.Matcher.replaceAll(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at com.jai.SecLargest.main(SecLargest.java:13)

I am not able to figure out why this exception is coming?

3 Answers 3

20

String.replaceAll ends up using (or being equivalent to using) Matcher.replaceAll, which includes this in the documentation:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

While you could escape the backslash as per AlexR's answer, I would strongly recommend that you use replace instead:

String y = x.replace('/', '\\');

That's a lot clearer, IMO - don't use replaceAll unless you're really trying to express a pattern via regular expressions.

Also note that as written your code would be a no-op anyway; strings are immutable in Java, so the replaceAll method (and similar ones) return a reference to a new string with the modificiations made.

Sign up to request clarification or add additional context in comments.

Comments

8

You should say x.replaceAll("/", "\\\\");

Back slash \ must be escaped twice: once of regular expressions engine and once for java itself.

Comments

0

You can also use quoteReplacement() method, in case you really need a regex.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.