Java: replaceAll doesn't work well with backslash?

前端 未结 9 1406
北荒
北荒 2021-01-25 12:56

I\'m trying to replace the beginning of a string with backslashes to something else. For some weird reason the replaceAll function doesn\'t like backslashes.

Str         


        
相关标签:
9条回答
  • 2021-01-25 13:35

    replaceAll() uses regexps which uses the backslash as an escape character. Moreover, Java String syntax also uses the backslash as an escape character. This means that you need to double all your backslashes to get what you want:

    String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
    jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
    
    0 讨论(0)
  • 2021-01-25 13:38
    jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
    

    For each '\' in your string you should put '\\' in the replaceAll method.

    0 讨论(0)
  • 2021-01-25 13:43

    You need to double each backslash (again) as the Pattern class that is used by replaceAll() treats it as a special character:

    String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
    jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
    

    A Java string treats backslash as an escape character so what replaceAll sees is: \\\\xyz\\abc. But replaceAll also treats backslash as an escape character so the regular expression becomes the characters: \ \ x y z \ a b c

    0 讨论(0)
  • 2021-01-25 13:43

    The replaceAll method uses regular expressions, which means that you have to escape slashes. In your case it might make sense to use String.replace instead:

    String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
    jarPath = jarPath.replace("\\\\xyz\\abc", "z:");
    
    0 讨论(0)
  • 2021-01-25 13:47

    replaceAll expects a regular expression as its input string, which is then matched and replaced in every instance. A backslash is a special escape character in regular expressions, and in order to match it you need another backslash to escape it. So, to match a string with "\", you need a regular expression with '"\"`.

    To match the string "\\\\xyz\\abc" you need the regular expression "\\\\\\\\xyz\\\\abc" (note an extra \ for each source \):

    String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
    jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
    
    0 讨论(0)
  • 2021-01-25 13:47

    Just got into a similar problem.

    If you use backslash() in the second section of the replaceAll function, the backslashes will dissapear, to avoid that, you can use Matcher class.

    String assetPath="\Media Database\otherfolder\anotherdeepfolder\finalfolder";
    
    String assetRemovedPath=assetPath.replaceAll("\\\\Media Database(.*)", Matcher.quoteReplacement("\\Media Database\\_ExpiredAssets")+"$1");
    
    system.out.println("ModifiedPath:"+assetRemovedPath);
    

    Prints:

    \Media Database\_ExpiredAssets\otherfolder\anotherdeepfolder\finalfolder
    

    hope it helps!

    0 讨论(0)
提交回复
热议问题