2

Why does the following not work:

      String test = "hello\"world".replaceAll("\"", "\\\"");
      System.out.println(test);

What I'm trying to do is replace any occurrence of " with \".

So I want to get as output:

hello\"world
3
  • 1
    You're escaping the ". Try .replaceAll("\\"", "\\\""); Commented Jul 10, 2012 at 16:34
  • 1
    This does not even compile... Commented Jul 10, 2012 at 16:36
  • Why do you think you need to do this? Commented Jul 11, 2012 at 1:50

3 Answers 3

6

Regular expressions are overkill for this.

myString.replace("\"", "\\\"")

should do just fine and is more readable to someone familiar with the core libraries.

The replace method just replaces one substring with another.

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".

Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the best solution.
Yes, I agree! An obvious, but probably easily overlooked solution. thanks.
0

You need to two more \\ to escape the escape character, for a total of 5 \s.

\\ - escape the escape character

\\ - to display the character

\ - to escape the quote.

Try:

String test = "hello\"world".replaceAll("\"", "\\\\\"");

Comments

0
String test = "hello\"world".replaceAll("\"", "\\\\\"");
System.out.println(test);

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.