Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing single '\' with '\\' in Java

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);
    }
}
like image 570
Husain Sanwerwala Avatar asked Jan 06 '13 14:01

Husain Sanwerwala


People also ask

How do you replace a single quote in Java?

This uses String. replace(CharSequence, CharSequence) method to do string replacement. Remember that \ is an escape character for Java string literals; that is, "\\'" contains 2 characters, a backslash and a single quote.

How do you replace only one occurrence of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.

How do you replace a single character in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.


1 Answers

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

    str = str.replaceAll("\\\\", "\\\\\\\\");
like image 190
Adam Sznajder Avatar answered Oct 14 '22 01:10

Adam Sznajder