且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用字符串中的 `\r` 替换 `\\r`

更新时间:2022-11-14 14:23:56

使用 replaceAll 你将不得不使用 .replaceAll("\\\\r", "\r"); 因为

With replaceAll you would have to use .replaceAll("\\\\r", "\r"); because

  • 要在正则表达式中表示 \ 您需要对其进行转义,因此您需要使用 pass \\ 到正则表达式引擎
  • 但是要为单个 \ 创建字符串文字,您需要将其写为 "\\".
  • to represent \ in regex you need to escape it so you need to use pass \\ to regex engine
  • but and to create string literal for single \ you need to write it as "\\".

更清晰的方法是使用 replace("\\r", "\r"); 它将自动转义所有正则表达式元字符.

Clearer way would be using replace("\\r", "\r"); which will automatically escape all regex metacharacters.