0

I want to replace a special character " with \" in string. I tried str = str.replaceAll("\"","\\\"); But this doesnt work.

Vibhuti
  • 702
  • 1
  • 7
  • 21
  • possible duplicate of [Backslash problem with String.replaceAll](http://stackoverflow.com/questions/1701839/backslash-problem-with-string-replaceall) – oers Mar 01 '12 at 08:06

3 Answers3

2

The closing quotes are missing in the 2nd parameter. Change to:

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

Also see this example.

scessor
  • 15,995
  • 4
  • 43
  • 54
0

You have to escape the \ by doubling it:\\

Code example:

String tt = "\\\\terte\\";
System.out.println(tt);
System.out.println(tt.replaceAll("\\\\", "|"));

This gives the following output:

\\terte\
||terte|
tom
  • 2,735
  • 21
  • 35
0

String.replaceAll() API:

Replaces each substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

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.

Btw, it is duplicated question.

Community
  • 1
  • 1
d1e
  • 6,372
  • 2
  • 28
  • 41