Reputation: 25143
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?
Upvotes: 3
Views: 7471
Reputation: 735
You can also use quoteReplacement() method, in case you really need a regex.
Upvotes: 0
Reputation: 1500135
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.
Upvotes: 20
Reputation: 115328
You should say x.replaceAll("/", "\\\\");
Back slash \
must be escaped twice: once of regular expressions engine and once for java itself.
Upvotes: 8