java

时间:2016-04-13 15:56:55

标签: java json

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"

但是当我在文件中有相同的内容并使用以下代码时,没有任何变化。

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();

,输出与文件内容相同:

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

我认为我在删除文件中的\时遇到了一些问题。我查看了其他替换所有问题,并尝试过,但没有一个在我的情况下有用。

1 个答案:

答案 0 :(得分:1)

您应该改为replace("\\\"", "\"")

方法replaceAll()将正则表达式作为第一个参数,将正则表达式替换作为第二个参数。方法replace()采用两个普通字符串,不对它们应用任何解释。

当您调用replaceAll("\\\"", "\"")时,程序使用正则表达式字符串\"并将其替换为字符串"。但是正则表达式字符串\"只是意味着",因为你正在逃避双重引用而没有效果。如果你真的想用replaceAll()来完成这项工作,你可以写replaceAll("\\\\\"", "\"")。但这不必要地复杂化,所以只需使用replace()方法。