22

I have string variable strVar with value as ' "value1" ' and i want to replace all the double quotes in the value with ' \" '. So after replacement value would look like ' \"value1\" '

How to do this in java? Kindly help me.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
net user
  • 573
  • 2
  • 8
  • 21
  • Does your code compile? is `' "value1" '` what you see in the source code or what you see when you print it out? – Hans Z Oct 10 '13 at 15:20

6 Answers6

57

You are looking for

str = str.replace("\"", "\\\"");

DEMO

I would avoid using replaceAll since it uses regex syntax which you don't need and which would complicate things since \ as also special character in regex for:

  • target describing what to replace,
  • replacement (where \ is special character used to escape other special character $).

In other words to create replacement representing \ we need to escape that \ with another \ like \\.

BUT that is not the end since \ is also special character in String literals - for instance we can use it to escape " like \" or to create special characters like tabulation "\t".
So to represent \ in String literal we also need to escape it there by another \ like "\\".

This means, to represent \ in replacement we need to escape it twice:

  • once in regex syntax, \\ -> \
  • and once in string literal "\\\\" -> \\

So code using replaceAll could look like:

str = str.replaceAll("\"", "\\\\\""); 
//replacement contains `\\\\` to represent `\`, and `\"` to represent `"`

or if we want to let regex engine handle escaping for us:

str = str.replaceAll("\"", Matcher.quoteReplacement("\\\""));

With replace method we don't need to worry about regex syntax and can focus only simple text. So to create String literal representing \ followed by " all we need is "\\\".

Pshemo
  • 122,468
  • 25
  • 185
  • 269
11

actually it is: strVar.replaceAll("\"", "\\\\\"");

Manuel Manhart
  • 4,819
  • 3
  • 24
  • 28
5

For example take a string which has structure like this--->>>

String obj = "hello"How are"you";

And you want replace all double quote with blank value or in other word,if you want to trim all double quote.

Just do like this,

String new_obj= obj.replaceAll("\"", "");
JSK NS
  • 3,346
  • 2
  • 25
  • 42
0

Strings are formatted with double quotes. What you have is single quotes, used for chars. What you want is this:

String foo = " \"bar\" ";

Aaron
  • 992
  • 3
  • 15
  • 33
0

This should give you what you want;

System.out.println("'\\\" value1 \\\"'");
dinukadev
  • 2,279
  • 17
  • 22
0

To replace double quotes

str=change condition to"or"      

str=str.replace("\"", "\\"");

After Replace:change condition to\"or\"

To replace single quotes

str=change condition to'or'      

str=str.replace("\'", "\\'");

After Replace:change condition to\'or\'

Himanshu
  • 4,327
  • 16
  • 31
  • 39
Shobha
  • 9
  • 3