Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - escaping double quotes in string from file

Tags:

java

regex

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?

like image 638
Pavel_K Avatar asked Nov 24 '15 12:11

Pavel_K


People also ask

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 escape double quotes in double quotes in Java?

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.

How can I escape a double quote inside double quotes?

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.

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.


1 Answers

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);
}
like image 66
GaspardP Avatar answered Sep 21 '22 18:09

GaspardP