Replacing single '\' with '\\' in Java

后端 未结 6 1604
离开以前
离开以前 2020-12-07 01:23

How do I replace a single \'\\\' with \'\\\\\'? When I run replaceAll() then I get this error message.

Exception in t         


        
6条回答
  •  醉酒成梦
    2020-12-07 01:44

    You could use Pattern.quote to make it easier for you to escape the value, such as:

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

    or, you can just use String.replace:

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

    See: Pattern.quote, String.replace and Matcher.quoteReplacement

提交回复
热议问题