0

我有不喜欢美元符号的代码,必须在替换时可见。

String s1= "this is amount <AMOUNT> you must pay";
s1.replaceAll("<AMOUNT>", "$2.60");
System.out.print(s1);

我有例外java.lang.IllegalArgumentException: Illegal group reference

我渴望得到字符串"this is amount $2.60 you must pay"

如何更改我的代码以获得所需的结果?

4

6 回答 6

5

如果您不需要使用正则表达式(您似乎不需要),请replace改用:

s1 = s1.replace("<AMOUNT>", "$2.60");
于 2013-04-02T11:32:31.273 回答
3

您必须像这样更改代码:

    String s1= "this is amount <AMOUNT> you must pay";
    s1 = s1.replaceAll("<AMOUNT>", "\\$2.60");
    System.out.print(s1);

1) 转义$字符

2)您需要保存replaceAll方法的结果,因此s1再次将其分配给。

于 2013-04-02T11:32:59.073 回答
2

只需使用替换即可。无需使用正则表达式。

s1 = s1.replace("<AMOUNT>", "$2.60");
于 2013-04-02T11:33:55.700 回答
0

正则表达式使用特殊字符$来指示表达式中的组。这就是你感到困惑的原因。如果你想要字面的东西,就逃避它。

public static void main(String[] args) {  
    String s1= "this is amount <AMOUNT> you must pay";
    System.out.print(s1.replaceAll("<AMOUNT>", "\\$2.60"));
}     
于 2013-04-02T11:33:23.097 回答
0

不使用正则表达式时,应使用replace()。

此外,您应该将生成的字符串存储在其他地方,例如

String s1 = "this is amount <AMOUNT> you must pay";
String s2 = s1.replace("<AMOUNT>", "$2.60");
System.out.println(s2);
于 2013-04-02T11:34:34.717 回答
0

在符号\\前使用双斜杠。$

String s1 = "this is amount <AMOUNT>you must pay";
s1 =s1.replaceAll("<AMOUNT>", "\\$2.60");
System.out.print(s1);
于 2013-04-02T11:43:33.947 回答