[英]java:replacing “ with \”
How can I escape the double quotes in a string? 如何在字符串中转义双引号? For eg,
例如
input: "Nobody"
output: \"Nobody\"
I tried sth like this,which is not working: 我试过这样的东西,这不起作用:
String name = "Nobody";
name.replaceAll("\"", "\\\"");
Because your string "Nobody" doesn't have any double quotes in it! 因为您的字符串“ Nobody”中没有任何双引号!
String name = "Nobo\"dy";
name = name.replaceAll("\"", "\\\\\"");
System.out.println(name);
Besides, you don't need a RegEx for such a simple replacement. 此外,您不需要RegEx即可进行如此简单的替换。
Just try 你试一试
name = name.replace("\"", "\\\"");
adarshr is right but also, notice that you are ignoring the returned string, do it like this: adarshr是正确的,但也请注意,您忽略了返回的字符串,请执行以下操作:
String name = "Nobody";
name = name.replaceAll("\"", "\\\"");
Strings in java are imutable Java中的字符串是不可更改的
Edit: Since I wrote that, adarshr has changed his answer to the better (if anyone wonder why I wrote that) 编辑:自从我写那封信以来,adarshr的回答就变的更好了(如果有人怀疑我为什么写那封信)
Take a look at http://www.bradino.com/javascript/string-replace/ as it gives tips on replacing all. 请看一下http://www.bradino.com/javascript/string-replace/ ,它提供了替换所有内容的提示。
You can do just one with: 您可以执行以下一项操作:
var name = '"Nobody"'; var name ='“ Nobody”'; name = name.replace("\\"", "\\\\"");
name = name.replace(“ \\”“,” \\\\“”);
Regards 问候
AJ AJ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.