问题描述
代码如下:System.out.println("'");System.out.println("\'");System.out.println("\'");System.out.println("\"");String a = "'"";System.out.println("1" + a.replace("'", "'"));System.out.println("2" + a.replace("'", "\'"));System.out.println("3" + a.replace("'", "\'"));System.out.println("4" + a.replace("'", "\\'"));System.out.println("5" + a.replaceAll(""", "\""));System.out.println("6" + a.replaceAll(""", "\\""));运行结果:'''"1'"2'"3'"4\'"5'"6'"问题:3中第二个参数字面值为',结果输出为';为啥5中第二个参数字面值为",结果输出不是"而是"?怎么想都想不明白啊。
解决方案
1、 ' 和 ' --都输出--> ' 也就是写不写都一样2、"3" + a.replace("'", "\'")3\'" ---> 3'" 即\ --> '--->' "--->"3、replaceAll是正则表达式替换"5" + a.replaceAll(""", "\"")即public String replaceAll(String regex, String replacement) { return Pattern.compile(regex).matcher(this).replaceAll(replacement);}---------->public String replaceAll(String replacement) { reset(); boolean result = find(); if (result) { StringBuffer sb = new StringBuffer(); do { appendReplacement(sb, replacement); result = find(); } while (result); appendTail(sb); return sb.toString(); } return text.toString(); }重点是 public Matcher appendReplacement(StringBuffer sb, String replacement) { // If no match, return error if (first < 0) throw new IllegalStateException("No match available"); // Process substitution string to replace group references with groups int cursor = 0; StringBuilder result = new StringBuilder(); while (cursor < replacement.length()) { char nextChar = replacement.charAt(cursor); if (nextChar == '\') { cursor++; nextChar = replacement.charAt(cursor); result.append(nextChar); cursor++; } else if (nextChar == '$') { // Skip past $ cursor++; // A StringIndexOutOfBoundsException is thrown if // this "$" is the last character in replacement // string in current implementation, a IAE might be // more appropriate. nextChar = replacement.charAt(cursor); int refNum = -1; if (nextChar == '{') { cursor++; StringBuilder gsb = new StringBuilder(); while (cursor < replacement.length()) { nextChar = replacement.charAt(cursor); if (ASCII.isLower(nextChar) || ASCII.isUpper(nextChar) || ASCII.isDigit(nextChar)) { gsb.append(nextChar); cursor++; } else { break; }此处红色部分 即如果匹配\ 那么跳过,则5'\" ---> 5'"--得到-->5'"
解决方案二:
System.out.println("5" + a.replaceAll(""", "\""));这里面替换相当于把 " 替换成 " ;之前a中的"相当于"所以出去是 5'"
解决方案三:
引用3中第二个参数字面值为',结果输出为';为啥5中第二个参数字面值为",结果输出不是"而是"?怎么想都想不明白啊。那是因为你只想到第3行的“\'”中的反斜杠是转义字符。却没有意识到第5行的第2个参数中的“'”,这里面的反斜杠也是个转义字符。也就是说 "'" 和 "'" 在内存中的表示是完全一样的。System.out.println("'" .equals( "'" )) ===> true
解决方案四:
[url]http://cadillac.iteye.com/blog/553187[/url],希望能帮到你。