Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace "\" with "" in java

Tags:

java

string

regex

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:
like image 590
Zakharov Roman Avatar asked Aug 03 '12 21:08

Zakharov Roman


2 Answers

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("\\", "");
like image 161
Jon Skeet Avatar answered Oct 12 '22 02:10

Jon Skeet


\\ 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("\\"), "");
like image 41
MByD Avatar answered Oct 12 '22 01:10

MByD