Java replaceAll 操作如何使用反斜杠?

How Java replaceAll operation works with backslashes?

为什么我需要四个反斜杠 (\) 才能在 String 中添加一个反斜杠?

String replacedValue = neName.replaceAll(",", "\\,");

在上面的代码中,您可以检查我必须替换 \, 中的所有逗号 (,),但我必须再添加三个反斜杠 (\) ?

谁能解释一下这个概念?

转义一次 Java,第二次转义正则表达式。

\ -> \ -> \\

或者由于您实际上并没有使用正则表达式,请采纳 khelwood 的建议并使用 replace(String,String),这样您只需转义一次。

String.replaceAll(regex, replacement) 的文档指出:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll.

Matcher.replaceAll(replacement) 的文档然后指出:

backslashes are used to escape literal characters in the replacement string

所以更清楚地说,当您替换为 \, 时,就好像您在转义逗号一样。但是你真正想要的是 \ 字符,所以你应该用 \, 来转义它。由于Java中的\也需要转义,所以替换String变成\\,.

如果你很难记住这一切,你可以使用方法Matcher.quoteReplacement(s),其目标是正确转义替换部分。您的代码将变为:

String replacedValue = neName.replaceAll(",", Matcher.quoteReplacement("\,"));

你必须首先转义反斜杠,因为它是一个文字(给出 \),然后因为正则表达式再次转义它(给出 \\)。

因此这个-

String replacedValue = neName.replaceAll(",", "\\,");  // you need ////

您可以使用 replace 而不是 replaceAll-

 String replacedValue = neName.replace(",", "\,"); 

\用于转义序列

例如

  • 转到下一行然后使用 \n\r
  • 选项卡 \t
  • 同样要打印 \ 这在字符串文字中是特殊的,你必须用另一个 \ 来转义它,这给了我们 \

现在 replaceAll 应该与正则表达式一起使用,因为您没有使用正则表达式,请按照评论中的建议使用 replace

String s = neName.replace(",", "\,");