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?
0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
But that would remove all "\", what if you just want to remove one not double \\? So something like :) becomes :) but :\\ also becomes :\ ?
6

You can simply use String.replaceAll()

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

1 Comment

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("\\\\", "")
-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.