Search code examples
javastringreplaceall

How to remove all '\' characters from a string in java


In my code I have a string, from which I need to remove all the "\" (Backslash) from. I'm trying to use String.replaceAll but it's throwing the Exception: "String literal is not properly closed by a double quote."

String links = new String(image[0]);
String changed = links.replaceAll("\", "");

" input - Image[0] " has links with a bunch of "\ / \ /" going on inside them I tried to post one but Stack Overflow edited the link to not have the "\"


Solution

  • Modify the regular expression with four backward slash "\\\\" in the above program. This will resolve the exception. The regular expression string will convert the four backward slash to 2 backward slash. The two backward slash “\\” is identified as single slash in regular expression matching.

    public class Test {
        public static void main(String[] args) {
            String links = new String("data \\");
            String changed = links.replaceAll("\\\\", "");
            System.out.println(changed);
        }
    }