java中的转义引号功能不起作用
我需要在打印字符串之前转义字符串中的引号。
我编写了一个函数,使用字符数组尽可能明确。但这个函数似乎所做的就是打印出它自己的输入:
public static String escapeQuotes(String myString) {
char[] quote=new char[]{'"'};
char[] escapedQuote=new char[]{'\\' , '"'};
return myString.replaceAll(new String(quote), new String(escapedQuote));
}
public static void main(String[] args) throws Exception {
System.out.println("asd\"");
System.out.println(escapeQuotes("asd\""));
}
我希望它的输出是: 自闭症谱系障碍” asd\”
但是我得到的是: 自闭症谱系障碍” asd“
有什么想法可以正确地做到这一点吗?
谢谢
I need to escape quotes from a string before printing them out.
I've written a function, using char arrays to be as explicit as possible. But all this function seems to do is print out its own input:
public static String escapeQuotes(String myString) {
char[] quote=new char[]{'"'};
char[] escapedQuote=new char[]{'\\' , '"'};
return myString.replaceAll(new String(quote), new String(escapedQuote));
}
public static void main(String[] args) throws Exception {
System.out.println("asd\"");
System.out.println(escapeQuotes("asd\""));
}
I would expect the output of this to be:
asd"
asd\"
However what I get is:
asd"
asd"
Any ideas how to do this properly?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会尝试
replace
而不是replaceAll
。第二个版本是为正则表达式设计的,据我所知。编辑
来自替换所有文档
请注意,替换字符串中的反斜杠 (\) 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同
因此,第二个参数中的反斜杠是一个问题。
文档的直接链接
http://download .oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
I would try
replace
instead ofreplaceAll
. The second version is designed for regex, AFAIK.edit
From replaceAll docs
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string
So, backslash in second argument is being a problem.
The direct link to the docs
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
Java 提供了现成的方法来转义正则表达式和替换:
Java comes with readily available methods for escaping regexs and replacements:
您还需要将
\
转义为\\
否则原始字符串中的任何\
将保留\
并且解析器,认为特殊字符(例如"
)必须跟在\
后面会感到困惑。每个
\
或"
放入 Java 文字字符串的字符前面需要带有\
。您需要使用
replace
而不是replaceAll
,因为前者处理字符串,后者处理正则表达式。在您的情况下,正则表达式会更慢,并且需要更多反斜杠。replace
与CharSequence
一起使用,即本例中的String
从 Java 1.5 开始就存在。You also need to escape
\
into\\
Otherwise any\
in your original string will remain\
and the parser, thinking that a special character (e.g."
) must follow a\
will get confused.Every
\
or"
character you put into a Java literal string needs to be preceeded by\
.You want to use
replace
notreplaceAll
as the former deals with strings, the latter with regexps. Regexps will be slower in your case and will require even more backslashes.replace
which works withCharSequence
s i.e.String
s in this case exists from Java 1.5 onwards.