Java中的单引号替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3156251/
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
Single quotes replace in Java
提问by dpaksp
In Java I have:
在Java中,我有:
String str = "Welcome 'thanks' How are you?";
I need to replace the single quotes in str
by \'
, that is, when I print str
I should get output as Welcome \'thanks\' How are you
.
我需要替换str
by 中的单引号\'
,也就是说,当我打印时,str
我应该得到输出为Welcome \'thanks\' How are you
.
采纳答案by polygenelubricants
It looks like perhaps you want something like this:
看起来你可能想要这样的东西:
String s = "Hello 'thanks' bye";
s = s.replace("'", "\'");
System.out.println(s);
// Hello \'thanks\' bye
This uses String.replace(CharSequence, CharSequence)
method to do string replacement. Remember that \
is an escape character for Java string literals; that is, "\\'"
contains 2 characters, a backslash and a single quote.
这使用String.replace(CharSequence, CharSequence)
方法进行字符串替换。请记住,这\
是 Java 字符串文字的转义字符;也就是说,"\\'"
包含 2 个字符、一个反斜杠和一个单引号。
References
参考
回答by MarcoS
Use
用
"Welcome 'thanks' How are you?".replaceAll("'", "\\'")
You need two levels of escaping in the replacement string, one for Java, and one for the regular expression engine.
您需要在替换字符串中进行两级转义,一级用于 Java,一级用于正则表达式引擎。
回答by Jeshurun
This is what worked for me:
这对我有用:
"Welcome 'thanks' How are you?".replaceAll("\'", "\\'");
It prints:
它打印:
Welcome \'thanks\' How are you?
回答by fanfavorite
In case you come to this question like me with trying to escape for MySQL, you want to add a second single quote to escape:
如果你像我一样试图为 MySQL 转义而遇到这个问题,你想添加第二个单引号来转义:
str.replaceAll("\'","\'\'")
This would print:
这将打印:
Welcome ''thanks'' How are you?