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

后端 未结 6 1479
攒了一身酷
攒了一身酷 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:10

    This is because Java tries to give \ a special meaning in the replacement string, so that \$ will be a literal $ sign, but in the process they seem to have removed the actual special meaning of \

    While text.replaceAll("\\\\","/"), at least can be considered to be okay in some sense (though it itself is not absolutely right), all the three executions, text.replaceAll("\n","/"), text.replaceAll("\\n","/"), text.replaceAll("\\\n","/") giving same output seem even more funny. It is just contradicting as to why they have restricted the functioning of text.replaceAll("\\","/") for the same reason.

    Java didn't mess up with regular expressions. It is because, Java likes to mess up with coders by trying to do something unique and different, when it is not at all required.

提交回复
热议问题