如何将转义字符添加到 Java 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18471500/
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
How can I add escape characters to a Java String?
提问by Jigglypuff
If I had a string variable:
如果我有一个字符串变量:
String example = "Hello, I'm here";
and I wanted to add an escape character in front of every '
and "
within the variable(i.e. notactually escape the characters), how would I do that?
并且我想在每个变量的前面'
和"
内部添加一个转义字符(即实际上不是对字符进行转义),我该怎么做?
采纳答案by ironicaldiction
I'm not claiming elegance here, but i thinkit does what you want it to do (please correct me if I'm mistaken):
我不是在这里声称优雅,但我认为它可以做你想做的事情(如果我错了,请纠正我):
public static void main(String[] args)
{
String example = "Hello, I'm\" here";
example = example.replaceAll("'", "\\'");
example = example.replaceAll("\"", "\\\"");
System.out.println(example);
}
outputs
产出
Hello, I\'m\" here