替换为反斜杠

时间:2017-09-19 15:53:20

标签: java regex

所以,当我运行以下内容时,

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

基本上,我试图用转义的美元符号替换所有$ \$

1 个答案:

答案 0 :(得分:0)

你快到了:

thing = thing.replaceAll("\\$", "\\\\\\$");

你需要转义第一个$,否则它是一个表示输入结束的正则表达式命令字符。

第二个论点也需要大量的转义:

  • 第一次双重逃避以避免替换为文字$
  • 第二次和第三次双重转义以防止引用组号(转义的$字符)并添加实际的反斜杠

然后,更简单的解决方案,没有正则表达式

thing = thing.replace("$", "\\$");    

注意:后一个示例仍然使用Pattern s,但它在内部引用了参数作为文字。

相关问题