简体   繁体   English

替换包含“with \”的字符串?

[英]Replace string containing “ with \”?

How can I replace string containing " with \\" ? 如何替换包含" with \\"字符串?

replace(""","\\"") is not working for me. replace(""","\\"")对我不起作用。

public static String replaceSpecialCharsForJson(String str){
    return str.replace("'","\'")
              .replace(":","\\:")
              .replace("\"","\"")
              .replace("\r", "\\r")
              .replace("\n", "\\n");
} 

You can try with: 您可以尝试:

replace("\"","\\\"")

Since both " and \\ are metacharacters , you have to escape them with \\ 由于这两种"\\元字符 ,你有逃脱他们\\

试试这个:

replace("\"","\\\"");

Every slash as part of a string needs to be escaped. 作为字符串一部分的每个斜杠都需要进行转义。 So if you want a string to look like "\\\\" , your code will have to contain String s = "\\\\\\\\" . 因此,如果您希望字符串看起来像"\\\\" ,则您的代码必须包含String s = "\\\\\\\\" Ugly but true. 丑陋而真实。

The same goes for any other special character that might be interpreted. 对于可能被解释的任何其他特殊字符也是如此。 Quotes and colons inclusive. 行情和冒号包括在内。 This means " \\ " " will look like " \\\\ \\" " (Added spaces to make separate escapes more visible) 这意味着" \\ " "看起来像" \\\\ \\" " (添加空格以使单独的转义更加明显)

Use: 使用:

str.replace("\"","\\\"")

So you escape the backslash. 所以你逃脱了反斜杠。

You want to 你想要

  • replace " (properly escaped: \\" ) 替换" (正确转义: \\"
  • with \\" (properly escaped: \\\\\\" ) . \\" (正确转义: \\\\\\"

The right call is: 正确的电话是:

replace("\"", "\\\"");

I tried this way. 我试过这种方式。 I don't know how much this helpful in your scenario 我不知道你的场景有多大帮助

String oldStr = String.valueOf('"');
String newStr = File.separator.concat(String.valueOf('"'));     
System.out.println(oldStr.replace(String.valueOf('"'),newStr));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM