Zakharov Roman
Zakharov Roman

Reputation: 779

replace "\" with "" in java

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:

Upvotes: 7

Views: 12056

Answers (3)

MByD
MByD

Reputation: 137322

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

Upvotes: 11

M Abbas
M Abbas

Reputation: 6479

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 \

Upvotes: 10

Jon Skeet
Jon Skeet

Reputation: 1500535

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

Upvotes: 25

Related Questions