1 String value="''''";
2 value = value.replaceAll("'", "\\'");
3 System.out.println(value);
4 System.out.println("\\'\\'\\'\\'");语句3的输出为 ''''
语句4的输出为 \'\'\'\'value replaceAll() 后的结果的结果不是 "\\'\\'\\'\\'"? 那应该是什么?
为什么会这样?

解决方案 »

  1.   

    replaceAll这个方法是以正则表达式为基础的.如果你用过其它语言的正则表达式,那么你一眼就能看出反斜杠的与众不同。在其它语言里,"\\"的意思是"我只是要在正则表达式里插入一个反斜杠。没什么特别的意思。"但是在Java里,"\\"的意思是"我要插入一个正则表达式的反斜杠,所以跟在它后面的那个字符的意思就变了。"举例来说,如果你想表示一个或更多的"单词字符",那么这个正则表达式就应该是"\\w+"。如果你要插入一个反斜杠,那就得用"\\\\"。不过像换行,跳格之类的还是只用一根反斜杠:"\n\t"。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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.而System.out.println("\\'\\'\\'\\'");这个里面第一个斜扛是转义符,后面的斜扛是被转义的.
      

  2.   

    首先"\"是转义字符
    value = value.replaceAll("'", "\\'");
    后的结果是
    value ="\'\'\'\'";
    然后
    System.out.println(value);
    结果自然是''''
    也就是说这两个步骤中转义字符都发生了作用,
    System.out.println("\\'\\'\\'\\'");
    只发生一次转义,所以结果为 \'\'\'\'
      

  3.   

    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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
    第一个value你操作了两次当然转义了2次,而后一个操作了一次当然就转义一次了
    所以才像你所说的那个结果。
    建议楼主看看jdk   有关这方面的东西在Package java.util.regex.pattern和java.util.regex.Matcher.replaceAll下