Sunil Kumar
Sunil Kumar

Reputation: 9

Java String replace " with \"

I have to replace " with \" in java , I tried

String.replaceall("\"","\\\"")

but it dint work

Thanks in advance

Upvotes: 0

Views: 93

Answers (2)

ajb
ajb

Reputation: 31689

According to the javadoc, replaceAll does regular expression matching. That means that the first parameter is treated as a regular expression, and the second parameter also has some characters with special meanings. See the javadoc.

The " character isn't special in regular expressions, so you don't need to do anything with it. But for the replacement expression, the backslash is special. If you have a replacement string and you don't want any of the characters to be treated as special, the easiest way is to use Matcher.quoteReplacement:

s.replaceAll("\"",Matcher.quoteReplacement("\\\""))

Also note that this doesn't modify s at all. replaceAll returns a string and you have to assign it to something (perhaps s, perhaps something else). (I don't know whether you were making that mistake or not, but it's a very common one on StackOverflow.)

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201429

Assuming you want a literal \ then you need to escape it in your regular expression (the tricky part is that \ is itself the escape character). You can do something like,

String msg = "\"Hello\"";
System.out.println(msg);
msg = msg.replaceAll("\"", "\\\\\"");
System.out.println(msg);

Output (indicating the changing "s) is

"Hello"
\"Hello\"

Upvotes: 4

Related Questions