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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19299788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:49:56  来源:igfitidea点击:

how to replace "(double quotes) in a string with \" in java

javastringreplacestr-replace

提问by net user

I have string variable strVar with value as ' "value1" 'and i want to replace all the double quotes in the value with ' \" '. So after replacement value would look like ' \"value1\" '

我有一个值为 as 的字符串变量 strVar ,' "value1" '我想用' \" '. 所以替换后的值看起来像' \"value1\" '

How to do this in java? Kindly help me.

如何在java中做到这一点?请帮助我。

回答by Pshemo

You are looking for

你正在寻找

strVar = strVar.replace("\"", "\\"")

DEMO

演示

I would avoid using replaceAllsince it uses regex syntax in description of what to replace and how to replace, which means that \will have to be escaped in string "\\"but also in regex \\(needs to be written as "\\\\"string) which means that we would need to use

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

replaceAll("\"", "\\\"");

or probably little cleaner:

或者可能是小清洁工:

replaceAll("\"", Matcher.quoteReplacement("\\""))

With replacewe have escaping mechanism added automatically.

随着replace我们已经逃逸机制自动添加。

回答by Aaron

Strings are formatted with double quotes. What you have is single quotes, used for chars. What you want is this:

字符串用双引号格式化。您拥有的是单引号,用于chars。你想要的是这个:

String foo = " \"bar\" ";

String foo = " \"bar\" ";

回答by Manuel Manhart

actually it is: strVar.replaceAll("\"", "\\\\\"");

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

回答by dinukadev

This should give you what you want;

这应该给你你想要的;

System.out.println("'\\" value1 \\"'");

回答by Shobha

To replace double quotes

替换双引号

str=change condition to"or"      

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

After Replace:change condition to\"or\"

替换后:将条件更改为\"或\"

To replace single quotes

替换单引号

str=change condition to'or'      

str=str.replace("\'", "\'");

After Replace:change condition to\'or\'

替换后:将条件更改为\'或\'

回答by Soumya Ranjan Sethy

For example take a string which has structure like this--->>>

例如,取一个具有这样结构的字符串--->>>

String obj = "hello"How are"you";

And you want replace all double quote with blank value or in other word,if you want to trim all double quote.

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

Just do like this,

就这样做,

String new_obj= obj.replaceAll("\"", "");