1

I am trying to replace string containing " with \" , below is the program I tried

    String s="\"/test /string\"";
    s = s.replaceAll("\"", "\\\"");
    System.out.println(s);

But I get the same output as the string "/test /string". Why is my replace function is not working. If I do

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

then I get the output I want \"/test /string\" . Why is the former dint work , even though in code I am trying to replace " with \"

2

1 Answer 1

10

You're using String.replaceAll, which takes a regular expression as its inputs, including the replacement. As documented in Match.replaceAll():

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.

You're really just trying to do a straight replace with no regexes involved, so use String.replace instead:

s = s.replace("\"", "\\\"");
Sign up to request clarification or add additional context in comments.

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.