Why String.replaceAll() in java requires 4 slashes “\\\\” in regex to actually replace “\”?

后端 未结 6 1483
攒了一身酷
攒了一身酷 2020-11-27 13:17

I recently noticed that, String.replaceAll(regex,replacement) behaves very weirdly when it comes to the escape-character \"\\\"(slash)

For example consider there is

6条回答
  •  不知归路
    2020-11-27 13:59

    One way around this problem is to replace backslash with another character, use that stand-in character for intermediate replacements, then convert it back into backslash at the end. For example, to convert "\r\n" to "\n":

    String out = in.replace('\\','@').replaceAll("@r@n","@n").replace('@','\\');
    

    Of course, that won't work very well if you choose a replacement character that can occur in the input string.

提交回复
热议问题