Ayacys
Ayacys

Reputation: 1

Strange issue with replaceAll() in java

String random = "{\"url\":\"api.github.com/repos/SparkTC/stocator/issues/comments/206712399\",\"html_url\":\"github.com/SparkTC/stocator/issues/22#issuecomment-206712399\"";
System.out.println(random.replaceAll("\\\"", ""));

Output: {"url":"api.github.com/repos/SparkTC/stocator/issues/comments/206712399","html_url":"github.com/SparkTC/stocator/issues/22#issuecomment-206712399"

But when I have same content in a file and use the following code, nothing changes.

File file = new File("/Users/ayacs/Desktop/example.json");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = "", oldtext = "";
        while ((line = reader.readLine()) != null) {
            oldtext += line + "\r\n";
        }
        reader.close();

        String newtext = oldtext.replaceAll("\\\"", "\"");
        System.out.println(oldtext);
        System.out.println(newtext);
        FileWriter writer = new FileWriter("/Users/ayacs/Desktop/example.json");
        writer.write(newtext);
        writer.close();

and the output is same as the file content:

{\"url\":\"api.github.com/repos/SparkTC/stocator/issues/comments/206712399\",\"html_url\":\"github.com/SparkTC/stocator/issues/22#issuecomment-206712399\"

I think I'm having some problem with removing the \ in my file. I looked into other replaceAll problems posted too and tried but none were useful in my case.

Upvotes: 0

Views: 51

Answers (1)

Nayuki
Nayuki

Reputation: 18533

You should write instead replace("\\\"", "\"").

The method replaceAll() takes a regex pattern as the first argument and a regex replacement as the second argument. The method replace() takes two plain strings and does not apply any interpretation to them.

When you called replaceAll("\\\"", "\""), the program uses the regex string \" and replaces it with the string ". But the regex string \" simply means ", because you are escaping the double-quote which has no effect. If you actually wanted to use replaceAll() to do the job, you would write replaceAll("\\\\\"", "\""). But this is unnecessarily complicated, so simply use the replace() method instead.

Upvotes: 1

Related Questions