'How should I replace \" on the "

For example I have code like this

String text = "\\\"";
String after = text.replaceAll("\"", "\"") // I want to see " but have \"

How can I replace "\ on the " with replaceAll() ?



Solution 1:[1]

If I understood your question it can be

String after = text.replaceAll("\"", "").

But you have two different questions in title and post.

Maybe try read this first How can I make Java print quotes, like "Hello"?

Solution 2:[2]

You are using the wrong argument for the matcher. You need to escape both the \ as well as " in your regular expression.

\\ is the back slash and \\\" is the quotation mark.

String after = text.replaceAll("\\\\\"", "\"");

alternatively you can also just drop the backslash as per @bharathp's suggestion.

Solution 3:[3]

You can try to use Matcher.quoteReplacement. Its definition states:

Slashes (\) and dollar signs ($) will be given no special meaning.

Example:

String text = "\\\"";
System.out.println("before replaceAll: " + text);
String after = text.replaceAll(Matcher.quoteReplacement("\\"), "");
System.out.println("after replaceAll: " + after);

Output:

before replaceAll: \"
after replaceAll: "

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 thinkgruen
Solution 3