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\"
我认为删除文件中的\时遇到一些问题。我也研究了发布的其他replaceAll问题并进行了尝试,但对我来说没有一个有用。
最佳答案
您应该改为replace("\\\"", "\"")
。
方法replaceAll()
将正则表达式模式作为第一个参数,将正则表达式替换作为第二个参数。方法replace()
接受两个纯字符串并且不对它们应用任何解释。
当您调用 replaceAll("\\\"", "\"")
时,程序使用正则表达式字符串 \"
并将其替换为字符串 ”
。但正则表达式字符串 \"
只是表示 "
,因为您正在转义双引号,而双引号没有任何效果。如果您确实想使用 replaceAll()
来完成这项工作,您可以编写 replaceAll("\\\\\"", "\"")
。但这不必要地复杂,因此只需使用 replace()
方法即可。
关于java - java中replaceAll()的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603713/