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

后端 未结 6 1600
离开以前
离开以前 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:41

    You have to first scape the \ for the string and then scape it for the regex, it would be \\\\ for each slash.

    0 讨论(0)
  • 2020-12-07 01:44

    In a String literal, \ must be escaped with another \. And in a reges, a \ must also be escaped by another \\. So, you must escape every \ four times: \\\\.

    Another way is to use Pattern.quote("\\") (for the regex) and Matcher.quoteReplacement("\\\\") for the replacement string.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-07 01:49

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

    This one worked perfectly. filePath = C:\abc\

    0 讨论(0)
  • 2020-12-07 02:00

    String.replaceAll(String,String) is regex.
    String.replace(String,String) will do what you want.

    The following...

    String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes";
    System.out.println(str);
    str = str.replace("\\", "\\\\");
    System.out.println(str);
    

    Produces...

    C:\Documents and Settings\HUSAIN\My Documents\My Palettes
    C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes

    0 讨论(0)
  • 2020-12-07 02:03

    \ is also a special character in regexp. This is why you should do something like this:

        str = str.replaceAll("\\\\", "\\\\\\\\");
    
    0 讨论(0)
提交回复
热议问题