48

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

For example:

hai how are\ you?

I want only:

hai how are you?
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
zahir hussain
  • 3,711
  • 10
  • 29
  • 36

3 Answers3

108
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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • Hi, if theres a scenario where 'hai \how are\ you?' , how can we write the regular expression to remvo the last '\' which will result to hai \how are you? – Farid Arshad Jun 22 '21 at 08:16
  • But that would remove all "\", what if you just want to remove one not double \\? So something like :\) becomes :\) but :\\ also becomes :\ ? – M. H. Apr 03 '22 at 21:50
6

You can simply use String.replaceAll()

 String foo = "hai how are\\ you?";
 String bar = foo.replaceAll("\\\\", "");
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
  • 2
    Umm ... is that correct? Don't you need to escape the '\' twice? Once for the literal string and once for the regex; e.g. `foo.replaceAll("\\\\", "")` – Stephen C Feb 11 '10 at 05:35
-6

String foo = "hai how are\ you?"; String bar = foo.replaceAll("\\", ""); Doesnt work java.util.regex.PatternSyntaxException occurs.... Find out the reason!! @Alan has already answered.. good

String bar = foo.replace("\\", ""); Does work

Abhiram
  • 106
  • 6