Java: replaceAll doesn't work well with backslash?

前端 未结 9 1418
北荒
北荒 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:");
    

提交回复
热议问题