简体   繁体   中英

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.

You are looking for

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

DEMO

I would avoid using replaceAll since it uses regex syntax in description of what to replace and how to replace, which means that \\ will have to be escaped in string "\\\\" but also in regex \\\\ (needs to be written as "\\\\\\\\" string) which means that we would need to use

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

or probably little cleaner:

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

With replace we have escaping mechanism added automatically.

实际上是: strVar.replaceAll("\\"", "\\\\\\\\\\"");

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

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

String foo = " \\"bar\\" ";

这应该给你你想要的;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM