zahir hussain
zahir hussain

Reputation: 3739

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

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

For example:

hai how are\ you?

I want only:

hai how are you?

Upvotes: 48

Views: 125630

Answers (3)

Abhiram
Abhiram

Reputation: 116

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

Upvotes: -6

Alan Moore
Alan Moore

Reputation: 75232

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.

Upvotes: 110

Mark Elliot
Mark Elliot

Reputation: 77044

You can simply use String.replaceAll()

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

Upvotes: 6

Related Questions