net user
net user

Reputation: 593

how to replace "(double quotes) in a string with \" in java

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.

Upvotes: 23

Views: 132959

Answers (6)

Pshemo
Pshemo

Reputation: 124215

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 "\\\".

Upvotes: 59

Shobha
Shobha

Reputation: 7

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\'

Upvotes: 0

Soumya Ranjan Sethy
Soumya Ranjan Sethy

Reputation: 72

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("\"", "");

Upvotes: 6

dinukadev
dinukadev

Reputation: 2297

This should give you what you want;

System.out.println("'\\\" value1 \\\"'");

Upvotes: 0

Manuel Manhart
Manuel Manhart

Reputation: 5455

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

Upvotes: 11

Aaron
Aaron

Reputation: 1016

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

String foo = " \"bar\" ";

Upvotes: 0

Related Questions