简体   繁体   English

java:用“ \\”替换“

[英]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);
  1. Your string didn't have double quotes 您的字符串没有双引号
  2. You weren't reassigning name (remember that strings are immutable in Java) 您没有在重新分配名称(请记住,字符串在Java中是不可变的)
  3. Your regex wasn't exactly correct. 您的正则表达式并不完全正确。

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的回答就变的更好了(如果有人怀疑我为什么写那封信)

name.replaceAll(...) does not change name - it returns the string so you need to write: name.replaceAll(...)不会更改名称-它返回字符串,因此您需要编写:

name = name.replaceAll(...)

JavaDoc Java文档

besides that your string doesn't contain a " 除了您的字符串不包含“

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.

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