Anand
Anand

Reputation: 12152

Replacing '\' character in a Java String

I have a java string with "\\" character (extra '\' for escaping). I want to replace all the occurence of "\\" to "\". Any idea how it can be done? str.replaceAll("\\", "\") does not work. The problem is in replacing the \ character.

Upvotes: 1

Views: 310

Answers (2)

Yuriy Vikulov
Yuriy Vikulov

Reputation: 2499

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

"\" means \ cause of \ is an escape symbol

heh, even stackoverflow parser converts \ \ (without spaces) to single \ :-))

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258678

From the Java documentation:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Upvotes: 1

Related Questions