4

Here my String is looking like :-

sTest = AAAAA"1111

I want to replace double quote to a back ward slash and a double quotes(\")

I need the String Like

sTest = AAAAA\"1111
skaffman
  • 398,947
  • 96
  • 818
  • 769
Binaya
  • 837
  • 2
  • 7
  • 7

4 Answers4

3
String escaped = "AAAAA\"1111".replace("\"", "\\\"");

(Note that the replaceAll version handles regular expressions and is an overkill for this particular situation.)

dacwe
  • 43,066
  • 12
  • 116
  • 140
2

string.replace("\"", "\\\"")

You want to replace " with \". Since both " and \ have a specific meaning you must escape them correctly by adding a preceding \ before each one.

So " --> \" and \" --> \\\". And since you want the compiler to understand that this is a String, you need to wrap each string with double-quotes So " --> \" and "\"" --> "\\\"".

RonK
  • 9,472
  • 8
  • 51
  • 87
  • Thanks Ronk for ur suggetion. – Binaya May 30 '11 at 07:08
  • When you want to replace " with \", you also want to replace all other \ with \\. Hence the answer should probably be: `string.replaceAll("([\\\\\"])", "\\\\$1")` (replace \ and " with \\$1, given that $1 is the matched string in the regex). – Adrien Sep 22 '20 at 17:36
1

Although the other answers are correct for the single situation given, for more complicated situations, you may wish to use StringEscapeUtils.escapeJava(String) from Apache Commons Lang.

String escaped = StringEscapeUtils.escapeJava(string);
ILMTitan
  • 10,751
  • 3
  • 30
  • 46
0
System.out.println("AAAAA\"1111".replaceAll("\"", "\\\\\""));
MarcoS
  • 13,386
  • 7
  • 42
  • 63