Java: replaceAll doesn't work well with backslash?

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

提交回复
热议问题