如何在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中转义$? 的全部内容, 来源链接: utcz.com/qa/413647.html