I have to replace '\\'
with '\'
in Java. The code i am using is
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\", "\\") );
But i don't know why it is throwing 'StringIndexOutOfBoundsException'.
It says 'String index out of range: 1'
What could be the reason? I guess it is because, the first argument replaceAll accept a pattern. What could be the possible solution?
Stacktrace
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(String.java:558) at java.util.regex.Matcher.appendReplacement(Matcher.java:696) at java.util.regex.Matcher.replaceAll(Matcher.java:806) at java.lang.String.replaceAll(String.java:2000)
Answer Found
asalamon74 posted the code i required, but don't know why he deleted that. In any case here it is.
There is a bug already filed in Java bugs database. [ Thanks for this reference asalamon ]
yourString.replaceAll("\\\\", "\\\\");
Amazingly both search and replace string are same :) but still it does what i require.