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.
Add double quotes to String in java If you want to add double quotes(") to String, then you can use String's replace() method to replace double quote(") with double quote preceded by backslash(\").
Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') . The replace() method will return a new string with all double quotes removed.
If you want to remove all double quotes then you can use this code: string=string. replaceAll("\"", ""); You are replacing all double quotes with nothing.
If you are dealing with a char then simply do this: c == '"'; If c is equal to the double quote the expression will evaluate to true .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With