简体   繁体   English

Java中的转义报价功能不起作用

[英]Escape quote function in java not working

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. 我编写了一个函数,使用char数组尽可能明确。 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\\" 我希望它的输出是:asd“ asd \\”

However what I get is: asd" asd" 但是我得到的是:asd“ asd”

Any ideas how to do this properly? 任何想法如何正确地做到这一点?

Thanks 谢谢

I would try replace instead of replaceAll . 我会尝试replace而不是replaceAll The second version is designed for regex, AFAIK. 第二个版本是为正则表达式AFAIK设计的。

edit 编辑
From replaceAll docs 来自replaceAll文档
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) http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String,java.lang.String

You also need to escape \\ into \\\\ Otherwise any \\ in your original string will remain \\ and the parser, thinking that a special character (eg " ) must follow a \\ will get confused. 您还需要将\\转义为\\\\否则原始字符串中的任何\\都将保留\\和解析器,认为必须在\\后跟一个特殊字符(例如" )会感到困惑。

Every \\ or " character you put into a Java literal string needs to be preceeded by \\ . 放入Java文字字符串中的每个\\"字符都必须以\\开头。

You want to use replace not replaceAll as the former deals with strings, the latter with regexps. 您要使用replace而不是replaceAll因为前者处理字符串,后者处理正则表达式。 Regexps will be slower in your case and will require even more backslashes. 在您的情况下,正则表达式将变慢,并且需要更多的反斜杠。

replace which works with CharSequence s ie String s in this case exists from Java 1.5 onwards. CharSequence一起使用的replace ,即从Java 1.5开始存在String

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

Java comes with readily available methods for escaping regexs and replacements: Java随附了用于转义正则表达式和替换的现成方法:

public static String escapeQuotes(String myString) { 
  return myString.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("\\\"")); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM