Java: replaceAll doesn't work well with backslash?

前端 未结 9 1407
北荒
北荒 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:54

    Its doesn't like it because \ is the escape character in C like languages (even as an escape on this forum) Which makes it a poor choice for a file seperator but its a change they introduced in MS-DOS...

    The problem you have is that you have escape the \ twice so \\host\path becomes \\\\host\\path in the string but for the regex has to be escaped again :P \\\\\\\\host\\\\path

    If you can use a forward slash this is much simpler

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

    You can use replace() method also which will remove \\\\xyz\\abc from the String

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

    You can just use the replace method instead replaceAll in your use-case. If i'm not mistaken it's does not use regex.

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