Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 911
net user Avatar asked Oct 10 '13 15:10

net user


People also ask

How can I replace double quotes in a string in Java?

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

How do you remove double quotes from a string?

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.

How do you remove double quotes from text files in Java?

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.

How do you match double quotes in Java?

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 .


1 Answers

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.

like image 90
Pshemo Avatar answered Oct 01 '22 21:10

Pshemo