14

How do I replace a single '\' with '\\'? When I run replaceAll() then I get this error message.

Exception in thread "main" java.util.regex.PatternSyntaxException:
                           Unexpected internal error near index 1 \
                                                                  ^
    at java.util.regex.Pattern.error(Pattern.java:1713)
    at java.util.regex.Pattern.compile(Pattern.java:1466)
    at java.util.regex.Pattern.<init>(Pattern.java:1133)
    at java.util.regex.Pattern.compile(Pattern.java:823)
    at java.lang.String.replaceAll(String.java:2190)
    at NewClass.main(NewClass.java:13)
Java Result: 1

My code:

public class NewClass {
    public static void main(String[] args) {
        String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes";
        str = str.replaceAll("\\", "\\\\");
        System.out.println(str);
    }
}
Med
  • 45
  • 7
Husain Sanwerwala
  • 479
  • 2
  • 7
  • 13

6 Answers6

24

String.replaceAll(String,String) is regex.
String.replace(String,String) will do what you want.

The following...

String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes";
System.out.println(str);
str = str.replace("\\", "\\\\");
System.out.println(str);

Produces...

C:\Documents and Settings\HUSAIN\My Documents\My Palettes
C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes

Mike
  • 2,434
  • 1
  • 16
  • 19
14

\ is also a special character in regexp. This is why you should do something like this:

    str = str.replaceAll("\\\\", "\\\\\\\\");
Adam Sznajder
  • 9,108
  • 4
  • 39
  • 60
5

You have to first scape the \ for the string and then scape it for the regex, it would be \\\\ for each slash.

Javier Diaz
  • 1,791
  • 1
  • 17
  • 25
2

In a String literal, \ must be escaped with another \. And in a reges, a \ must also be escaped by another \\. So, you must escape every \ four times: \\\\.

Another way is to use Pattern.quote("\\") (for the regex) and Matcher.quoteReplacement("\\\\") for the replacement string.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

You could use Pattern.quote to make it easier for you to escape the value, such as:

str = str.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"));

or, you can just use String.replace:

str = str.replace("\\", "\\\\");

See: Pattern.quote, String.replace and Matcher.quoteReplacement

Tom Leese
  • 19,309
  • 12
  • 45
  • 70
0
filePath = filePath.replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\"));

This one worked perfectly.

OUTPUT:
filePath = C:\abc\
itronic1990
  • 1,231
  • 2
  • 4
  • 18