所以,当我运行以下内容时,
String thing = "y$xx$sss$$aaa";
thing = thing.replaceAll("$", "\\$");
System.out.println(thing);
我仍然以"y$xx$sss$$aaa"
作为输出。我也试过了
String thing = "y$xx$sss$$aaa";
thing = thing.replaceAll("$", "\\\\$");
System.out.println(thing);
和
String thing = "y$xx$sss$$aaa";
thing = thing.replaceAll("$", "\\\\\\\\$");
System.out.println(thing);
根据一些现有答案,但我一直收到错误Illegal group reference: group index is missing
。
基本上,我试图用转义的美元符号替换所有$
\$
答案 0 :(得分:0)
你快到了:
thing = thing.replaceAll("\\$", "\\\\\\$");
你需要转义第一个$
,否则它是一个表示输入结束的正则表达式命令字符。
第二个论点也需要大量的转义:
$
$
字符)并添加实际的反斜杠然后,更简单的解决方案,没有正则表达式:
thing = thing.replace("$", "\\$");
注意:后一个示例仍然使用Pattern
s,但它在内部引用了参数作为文字。