java 替换双引号(")

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5965452/
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-10-30 13:43:32  来源:igfitidea点击:

Replace double quotes(")

javastring

提问by Binaya

Here my String is looking like :-

这里我的字符串看起来像:-

sTest = AAAAA"1111

I want to replace double quote to a back ward slash and a double quotes(\")

我想将双引号替换为反斜杠和双引号 ( \")

I need the String Like

我需要像字符串一样

sTest = AAAAA\"1111

回答by dacwe

String escaped = "AAAAA\"1111".replace("\"", "\\"");

(Note that the replaceAllversion handles regular expressions and is an overkill for this particular situation.)

(请注意,该replaceAll版本处理正则表达式,对于这种特殊情况来说是一种矫枉过正。)

回答by RonK

string.replace("\"", "\\\"")

string.replace("\"", "\\\"")

You want to replace "with \". Since both "and \have a specific meaning you must escape them correctly by adding a preceding \before each one.

您想替换"\". 由于"\都具有特定含义,因此您必须通过\在每个之前添加前缀来正确地转义它们。

So "--> \"and \"--> \\\". And since you want the compiler to understand that this is a String, you need to wrap each string with double-quotes So "--> \"and "\""--> "\\\"".

所以"-->\"\"--> \\\"。并且由于您希望编译器理解这是一个字符串,因此您需要用双引号 So "-->\""\""-->将每个字符串括起来"\\\""

回答by ILMTitan

Although the other answers are correct for the single situation given, for more complicated situations, you may wish to use StringEscapeUtils.escapeJava(String)from Apache Commons Lang.

尽管其他答案对于给定的单一情况是正确的,但对于更复杂的情况,您可能希望使用Apache Commons Lang 中的StringEscapeUtils.escapeJava(String)

String escaped = StringEscapeUtils.escapeJava(string);

回答by MarcoS

System.out.println("AAAAA\"1111".replaceAll("\"", "\\\""));