How to remove the backslash in string using regex in Java?

Solution 1:

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

or

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

replaceAll() treats the first argument as a regex, so you have to double escape the backslash. replace() treats it as a literal string, so you only have to escape it once.

Solution 2:

You can simply use String.replaceAll()

 String foo = "hai how are\\ you?";
 String bar = foo.replaceAll("\\\\", "");