tags:

views:

240

answers:

3

how to remove the backslash in string using regex in java

example : String is "hai how are\ you?"

i want only hai how are you?.

please help me...

+2  A: 

You can simply use String.replaceAll()

 String foo = "hai how are\\ you?";
 String bar = foo.replaceAll("\\\\", "");
Mark E
hey realy thank u...........
zahir hussain
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
@Stephen, looks like you're correct, fixed accordingly
Mark E
@Oscar, should be good now.
Mark E
+1 It is :) ...
OscarRyz
+4  A: 
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
A: 

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