Replace "\" with "" in java

my question is pretty simple:

how to replace "\" with ""

I tried this:

str.replaceAll("\\", ""); 

but i get an exception

 08-04 01:14:50.146: I/LOG(7091): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1: 
+6
source share
3 answers

It is easier if you are not using replaceAll (which accepts a regular expression) for this - just use replace (which accepts a simple string). Do not use the regular expression form unless you really need regular expressions. This only complicates the situation.

Do not forget that just calling replace or replaceAll pointless, since the strings are immutable - you need to use the return result:

 String replaced = str.replace("\\", ""); 
+22
source

\\ after \ \ , which is also an escape character in regex try

 String newStr = str.replaceAll("\\\\", ""); 

(do not forget to assign a result)

Also, if you use some string as input where a regular expression is expected, it is safer to use IMO Pattern#quote :

 String newStr = str.replaceAll(Pattern.quote("\\"), ""); 
+11
source

You should try the following:

 str.replaceAll("\\\\", ""); 

\ should be escaped in regex =>, you should write \\ , and each \ should be escaped in java =>, so we have 4 \

+9
source

Source: https://habr.com/ru/post/922087/


All Articles