Vibhuti
Vibhuti

Reputation: 704

Replace a special character with other special character within string

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

Upvotes: 0

Views: 250

Answers (3)

tom
tom

Reputation: 2745

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|

Upvotes: 0

scessor
scessor

Reputation: 16115

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

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

Also see this example.

Upvotes: 2

d1e
d1e

Reputation: 6442

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.

Upvotes: 0

Related Questions