7

my question is quite simple:

how to replace "\" with "" ???

I tried this:

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

but I get en exception

08-04 01:14:50.146: I/LOG(7091): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
Gus
  • 6,719
  • 6
  • 37
  • 58
Zakharov Roman
  • 739
  • 3
  • 13
  • 31
  • possible duplicate of [replace String with another in java](http://stackoverflow.com/questions/5216272/replace-string-with-another-in-java) – Robert MacLean May 15 '13 at 07:55
  • possible duplicate of [Java how to replace slash?](http://stackoverflow.com/questions/5756748/java-how-to-replace-slash) – fglez May 16 '13 at 08:53

3 Answers3

25

It's simpler if you don't use replaceAll (which takes a regex) for this - just use replace (which takes a plain string). Don't use the regular expression form unless you really need regexes. It just makes things more complicated.

Don't forget that just calling replace or replaceAll is pointless as strings are immutable - you need to use the return result:

String replaced = str.replace("\\", "");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
11

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

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

(don't forget to assign the result)

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

String newStr = str.replaceAll(Pattern.quote("\\"), "");
MByD
  • 135,866
  • 28
  • 264
  • 277
10

You should try this:

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

The \ has to be escaped in regex => you should write \\, and each \ has to be escaped in java => thats why we have the 4 \

M. Abbas
  • 6,409
  • 4
  • 33
  • 46