Java: replaceAll doesn't work well with backslash?

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

提交回复
热议问题