如何用java中的\"替换字符串中的"(双引号)

net*_*ser 13 java string replace str-replace

我有字符串变量strVar值为' "value1" ',我想用值替换值中的所有双引号' \" '.所以在更换后的价值看起来像' \"value1\" '

如何在java中执行此操作?请帮助我.

Psh*_*emo 37

你在找

strVar = strVar.replace("\"", "\\\"")
Run Code Online (Sandbox Code Playgroud)

DEMO

我会避免使用,replaceAll因为它在描述要替换的内容和如何替换时使用正则表达式语法,这意味着\必须在字符串中转义,"\\"但也在regex中转义\\(需要写为"\\\\"字符串),这意味着我们需要使用

replaceAll("\"", "\\\\\"");
Run Code Online (Sandbox Code Playgroud)

或者可能是小清洁工:

replaceAll("\"", Matcher.quoteReplacement("\\\""))
Run Code Online (Sandbox Code Playgroud)

随着replace我们自动添加了转义机制.


小智 6

例如,采用具有如下结构的字符串--->>>

String obj = "hello"How are"you";
Run Code Online (Sandbox Code Playgroud)

并且您希望将所有双引号替换为空白值或换句话说,如果您想修剪所有双引号。

只要这样做,

String new_obj= obj.replaceAll("\"", "");
Run Code Online (Sandbox Code Playgroud)


Man*_*art 5

实际上它是: strVar.replaceAll("\"", "\\\\\"");