Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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

For example:

hai how are\ you? 

I want only:

hai how are you? 
like image 460
zahir hussain Avatar asked Feb 11 '10 05:02

zahir hussain


People also ask

How do you remove backslash from string?

To remove all backslashes from a string:Call the replaceAll method, passing it a string containing 2 backslashes as the first parameter and an empty string as the second - str. replaceAll('\\', '') . The replaceAll method returns a new string with all of the matches replaced.

How do you escape a slash in regex Java?

If you want to match a backslash in your regular expression, you'll have to escape it. Backslash is an escape character in regular expressions. You can use '\\' to refer to a single backslash in a regular expression. However, backslash is also an escape character in Java literal strings.

How do you remove a single slash in Java?

Replacing a Single Backslash( \ ) With a Double Backslash( \\ ) Using the replaceAll() Method. This is another solution that you can use to replace the backslashes. Here, we used the replaceAll() method that works fine and returns a new String object.


1 Answers

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.

like image 106
Alan Moore Avatar answered Sep 21 '22 12:09

Alan Moore