gpt4 book ai didi

java - java中如何转义$?

转载 作者:行者123 更新时间:2023-12-02 05:17:23 25 4
gpt4 key购买 nike

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

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 - java中如何转义$?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56286713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com