Search code examples
javastringescaping

How to replace "\" with "/" in java?


I have a string like s = "abc\def" and I want to replace "" with "/" and makes the string like "abc/def/".

I tried replaceAll("\\","/") but the compiler is giving error for string

error: illegal escape character String s="abc\def";


Solution

  • The issue is that Java uses \ as the string escape character, but also as the regex escape character, and replaceAll performs a regex search. So you need to doubly escape the backslash (once to make it a literal \ in the string, and once to make it a literal character in the regular expression):

    result = str.replaceAll("\\\\", "/");
    

    Alternatively, you don’t actually need regular expressions here, so the following works as well:

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

    Or, indeed, using the single-char replacement version:

    result = str.replace('\\', '/');