问题
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.
回答1:
You are looking for
strVar = strVar.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
replaceAll("\"", "\\\\\"");
or probably little cleaner:
replaceAll("\"", Matcher.quoteReplacement("\\\""))
With replace
we have escaping mechanism added automatically.
回答2:
actually it is:
strVar.replaceAll("\"", "\\\\\"");
回答3:
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("\"", "");
回答4:
Strings are formatted with double quotes. What you have is single quotes, used for char
s. What you want is this:
String foo = " \"bar\" ";
回答5:
This should give you what you want;
System.out.println("'\\\" value1 \\\"'");
回答6:
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\'
来源:https://stackoverflow.com/questions/19299788/how-to-replace-double-quotes-in-a-string-with-in-java