编程语言
首页 > 编程语言> > 如何在Java中转义$?

如何在Java中转义$?

作者:互联网

我正在尝试下面的代码,但出现错误

String x = "aaa XXX bbb";
    String replace = "XXX";
    String y = "xy$z";
    String z=y.replaceAll("$", "\\$");
    x = x.replaceFirst(replace, z);
    System.out.println(x);

错误

Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
    at java.util.regex.Matcher.appendReplacement(Unknown Source)
    at java.util.regex.Matcher.replaceFirst(Unknown Source)
    at java.lang.String.replaceFirst(Unknown Source)
    at Test.main(Test.java:10)

我想要结果

aaa xy$z bbb

解决方法:

请改用replace(),它不使用正则表达式,因为您根本不需要它们:

String x = "aaa XXX bbb";
String replace = "XXX";
String y = "xy$z";
x = x.replace(replace, y);
System.out.println(x);

如预期,这将打印aaa xy $z bbb.

标签:java,regex,special-characters
来源: https://codeday.me/bug/20191011/1889484.html