简体   繁体   中英

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. 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

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)

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 \\ .

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 CharSequence s ie String s in this case exists from Java 1.5 onwards.

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

Java comes with readily available methods for escaping regexs and replacements:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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