1

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.

4
  • Is your string 'my\string' or 'my\\string'. Do you want to replace one or two slashes? Commented Dec 2, 2011 at 10:45
  • "my\string" is invalid in java. its definitely "my\\string". Commented Dec 2, 2011 at 10:46
  • I'm not talking about the java string. If in java you have String x = "my\\string", the actual logical string is "my\string", right? Commented Dec 2, 2011 at 10:47
  • @LuchianGrigore thats correct! Commented Dec 2, 2011 at 10:48

2 Answers 2

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

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Oh irony... fixed the escaping issues in your answer!

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.