views:

3065

answers:

7

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.

+1  A: 

File.seperator is already escaped as is any string object so you are escaping them twice.

You only need to escape values that you are entering as a string literal.

Stevo3000
+7  A: 

Use String.replace instead of replaceAll to avoid it using a regex:

String original = MyConstants.LOCATION_PATH + File.seperator 
    + myObject.getStLocation();
System.out.println(original.replace("\\\\", "\\"));

Personally I wouldn't do it this way though - I'd create MyConstants.LOCATION_PATH_FILE as a File and then you could write:

File location = new File(MyConstants.LOCATION_PATH_FILE,
                         myObject.getStLocation());

which will do the right thing automatically.

Jon Skeet
That was just an example. take this, i have to replace '\\' with '\' in the string "hello\\!!\is\\that\\\\you" !
Rakesh Juyal
The closer you can make your example to reality, the more likely you are to get helpful answers. However, the use of just "replace" should still work fine.
Jon Skeet
A: 

I suspect the problem is that replaceAll() uses regexps and the backslash is an escape character in regexps as well as in Java - it might be necessary to double the number of backslashes.

In general you should always post the full stack trace of exceptions, it is much easier to diagnose the problem that way.

Michael Borgwardt
A: 

I believe what you need to do is:

System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\\\\\", "\\\\") );

The regular expression String is actually four backslashes, which is a regular expression that matches two backslashes.

The replacement String has to be four slashes as per Java documentation, from: http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)

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.

Jack Leow
+4  A: 

Well, i tried

    String test = "just a \\ test with some \\\\ and others \\\\ or \\ so";
    String result = test.replaceAll("\\\\", "\\\\");
    System.out.println(test);
    System.out.println(result);
    System.out.println(test.equals(result));

and got, as expected

just a \ test with some \\ and others \\ or \ so
just a \ test with some \\ and others \\ or \ so
true

What you really need is

string.replaceAll("\\\\\\\\", "\\\\");

to get

just a \ test with some \\ and others \\ or \ so
just a \ test with some \ and others \ or \ so
false

You want to find: \\
which needs to be escaped in the regex: \\\\
and escaped in Java: "\\\\\\\\"
same for the replacement

[]]

Carlos Heuberger
A: 
final StringBuilder result = new StringBuilder();
final StringCharacterIterator iterator = new StringCharacterIterator(str);
char character =  iterator.current();
while (character != CharacterIterator.DONE )
{
  if (character == '\\\\') {
     result.append("\\");
  }
  else {
    result.append(character);
  }

  character = iterator.next();
}

System.out.print(result);
Ujjwal
`if (character == '\\\\')` is a syntax error. You're trying to squeeze two backslashes into one `char` literal.
Alan Moore
A: 

cadena.replaceAll("\\","\\\\") Espero que te sirva.

Diego Santillan