0

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

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

but it dint work

Thanks in advance

1
  • Why? I usually find that these are non-questions, about operations that aren't necessary. Who is going to read this escaped quote? Only the Java compiler understands that. Commented Mar 10, 2016 at 6:39

2 Answers 2

4

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\"
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need for a regular expression here, though. For simple text replacements, a String#replace will do.
2

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.)

Comments

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.