开发者

Escape quote function in java not working

开发者 https://www.devze.com 2023-01-24 09:04 出处:网络
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

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\"");开发者_如何学Go
 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


I would try replace instead of replaceAll. 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 comes with readily available methods for escaping regexs and replacements:

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


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 not replaceAll 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 with CharSequences i.e. Strings in this case exists from Java 1.5 onwards.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号