字符串中包含双引号字符,要经过转化将双引号替换为反斜杠加双引号,并输出.
例如:
af"fd"fase
转换后输出
af\"fd\"fase
我用的字符串类的replaceAll("\"","\\\"")方法,为什么反斜杠不输出?
结果还是
af"fd"faseJava字符串正则表达式转义字符

解决方案 »

  1.   

    String str = "asdfa\"asdfasdf\"asdfasdf\"";

    str = str.replaceAll("\"",Matcher.quoteReplacement("\\\""));

    System.out.println(str);replaceAll第二个参数要是有正则的特殊字符的话,会引起问题的。
      

  2.   


    replaceAll
    public String replaceAll(String regex,
                             String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 
    调用此方法的 str.replaceAll(regex, repl) 形式与以下表达式产生的结果完全相同: Pattern.compile(regex).matcher(str).replaceAll(repl)
    注意,在替代字符串中使用反斜杠 (\) 和美元符号 ($) 与将其视为字面值替代字符串所得的结果可能不同;请参阅 Matcher.replaceAll。如有需要,可使用 Matcher.quoteReplacement(java.lang.String) 取消这些字符的特殊含义。 
    参数:
    regex - 用来匹配此字符串的正则表达式
    replacement - 用来替换每个匹配项的字符串 
    返回:
    所得 String 
    抛出: 
    PatternSyntaxException - 如果正则表达式的语法无效
    从以下版本开始: 
    1.4 
    另请参见:
    Pattern
      

  3.   

    replaceAll
    public String replaceAll(String regex,
                             String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 
    调用此方法的 str.replaceAll(regex, repl) 形式与以下表达式产生的结果完全相同: Pattern.compile(regex).matcher(str).replaceAll(repl)
    注意,在替代字符串中使用反斜杠 (\) 和美元符号 ($) 与将其视为字面值替代字符串所得的结果可能不同;请参阅 Matcher.replaceAll。如有需要,可使用 Matcher.quoteReplacement(java.lang.String) 取消这些字符的特殊含义。 
    参数:
    regex - 用来匹配此字符串的正则表达式
    replacement - 用来替换每个匹配项的字符串 
    返回:
    所得 String 
    抛出: 
    PatternSyntaxException - 如果正则表达式的语法无效
    从以下版本开始: 
    1.4 
    另请参见:
    Pattern
      

  4.   


    import java.util.regex.*;
    public class Test01 {
    public static void main(String[] args){
      Pattern p = Pattern.compile("\"");
      Matcher m = p.matcher("af\"fd\"fase");
      p(m.replaceAll("\\\\\""));
    }

    public static void p(Object obj){
    System.out.println(obj);
    }
    }System.out.println("af\"fd\"fase".replaceAll("\"","\\\\\""));af\"fd\"fase
      

  5.   


    嗯,这个问题解决了,谢谢!
    但是如果想把一条反斜杠换成两条怎么做呢?
    使用replaceAll("\\", Matcher.quoteReplacement("\\\\"))会报错,
    使用replace("\\", Matcher.quoteReplacement("\\\\"))结果不对.
      

  6.   


    主要是replaceAll这个函数在作怪,在这个函数的执行过程中,还要将斜杠做一次转义处理
    也就是"\\"传到replaceAll里面后,会变成"\",在它里面,又会将"\"当成转义字符比如replaceAll("\\","4"); 在当前java代码里,"\\" = \传到函数replaceAll里面后,就变成了"\", 它也把"\"当成是一个字符串,而这个字符串是无法识别的,就会报错综上,应该这样写:
    String s="af\\fd\\fase";
    System.out.println(s.replaceAll("\\\\","\\\\\\\\"));
      

  7.   


    呃,replaceAll("\\", Matcher.quoteReplacement("\\\\"))前面是一个正则表达式,这样写是会报错的。改成   replaceAll("\\\\", Matcher.quoteReplacement("\\\\"))
      

  8.   

    replace方法第一个参数是个字符串