Home > Software engineering >  How should I replace \" on the "
How should I replace \" on the "

Time:05-13

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() ?

CodePudding user response:

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"?

CodePudding user response:

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.

CodePudding user response:

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: "
  • Related