I have html string from file. I need to escape all double quotes. So I do this way:
String content=readFile(file.getAbsolutePath(), StandardCharsets.UTF_8);
content=content.replaceAll("\"","\\\"");
System.out.println(content);
However, the double quotes are not escaped and the string is the same as it was before replaceAll method. When I do
String content=readFile(file.getAbsolutePath(), StandardCharsets.UTF_8);
content=content.replaceAll("\"","^^^");
System.out.println(content);
All double quotes are replaced with ^^^.
Why content.replaceAll("\"","\\\"");
doesn't work?
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.
Escaping double quotes in Java String If we try to add double quotes inside a String, we will get a compile-time error. To avoid this, we just need to add a backslash (/) before the double quote character.
The basic double-quoted string is a series of characters surrounded by double quotes. If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters.
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.
It took me way too long in Java to discover Pattern.quote
and Matcher.quoteReplacement
. These will you achieve what you are trying to do here - which is a simple "find" and "replace" - without any regex and escape logic. The Pattern.quote
here would not be necessary but it shows how you can ensure that the "find" part is not interpreted as a regex string:
@Test
public void testEscapeQuotes()
{
String content="some content with \"quotes\".";
content=content.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("\\\""));
Assert.assertEquals("some content with \\\"quotes\\\".", content);
}
Remember that you can also use the simple .replace
method which will also "replaceAll" but will not interpret your parameters as regular expressions:
@Test
public void testEscapeQuotes()
{
String content="some content with \"quotes\".";
content=content.replace("\"", "\\\"");
Assert.assertEquals("some content with \\\"quotes\\\".", content);
}
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