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:
2

3 Answers 3

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("\\", "");
Sign up to request clarification or add additional context in comments.

1 Comment

I like the fact that you look at the bigger picture.
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("\\"), "");

Comments

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 \

2 Comments

While I think you are correct, you should explain why as well.
java escapes \ and regex needs to escape \ so 2X2 = 4 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.