开发者

java:replacing " with \"

开发者 https://www.devze.com 2023-02-19 05:15 出处:网络
How can I escape the double quotes in a string? For eg, input: \"Nobody\"开发者_Python百科 output:\\\"Nobody\\\"

How can I escape the double quotes in a string? For eg,

input: "Nobody"开发者_Python百科
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

0

精彩评论

暂无评论...
验证码 换一张
取 消