为什么将 All 替换为“非法组引用”失败?

2022-08-31 12:41:56

我需要更换

\\\s+\\$\\$ to $$

我用过

String s = "  $$";
s = s.replaceAll("\\s+\\$\\$","$$");

但它会引发异常

java.lang.IllegalArgumentException: Illegal group reference


答案 1

From String#replaceAll javadoc

请注意,替换字符串中的反斜杠 (\) 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同;请参阅 Matcher.replaceAll。如果需要,请使用 Matcher.quoteReplacement(java.lang.String) 来禁止显示这些字符的特殊含义。

因此,可以使用 Matcher#quoteReplacement 完成任意替换字符串的转义:

String s = "  $$";
s = s.replaceAll("\\s+\\$\\$", Matcher.quoteReplacement("$$"));

也可以使用 Pattern#quote 完成模式的转义

String s = "  $$";
s = s.replaceAll("\\s+" + Pattern.quote("$$"), Matcher.quoteReplacement("$$"));

答案 2

在第二个参数中使用:"\\$\\$"

String s="  $$";
s=s.replaceAll("\\s+\\$\\$","\\$\\$");
//or
//s=s.replaceAll("\\s+\\Q$$\\E","\\$\\$");

正则表达式替换参数中的 is 组符号$

所以你需要逃避它