简体   繁体   中英

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!

    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)
  3. Your regex wasn't exactly correct.

Besides, you don't need a RegEx for such a simple replacement.

Just try

    name = name.replace("\"", "\\\"");

adarshr is right but also, notice that you are ignoring the returned string, do it like this:

String name = "Nobody";
name = name.replaceAll("\"", "\\\"");

Strings in java are imutable

Edit: Since I wrote that, adarshr has changed his answer to the better (if anyone wonder why I wrote that)

name.replaceAll(...) does not change name - it returns the string so you need to write:

name = name.replaceAll(...)

JavaDoc

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.

You can do just one with:

var name = '"Nobody"'; name = name.replace("\\"", "\\\\"");

Regards

AJ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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