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

后端 未结 6 1457
攒了一身酷
攒了一身酷 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 14:08

    You need to esacpe twice, once for Java, once for the regex.

    Java code is

    "\\\\"
    

    makes a regex string of

    "\\" - two chars
    

    but the regex needs an escape too so it turns into

    \ - one symbol
    

提交回复
热议问题