java中的字符串replaceAll()

Mon*_*sha 4 java

你能解释一下输出吗?

String str = "Total Amount is AMOUNT";
String amount = "$10.00";
str = str.replaceAll("AMOUNT", amount);
System.out.println(str);
Run Code Online (Sandbox Code Playgroud)

什么是输出?它抛出异常

Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1
Run Code Online (Sandbox Code Playgroud)

通过删除$的工作.为什么?

Cod*_*der 12

String.replaceAll()接受正则表达式.

并且$在正则表达式中用于替换捕获的组.像$1代表第一个被捕集团的内容......等等.

在你的情况下,因为你根本不使用正则表达式 String.replace("AMOUNT", amount)

  • 如果不使用正则表达式,请不要使用正则表达式方法.为此+1. (3认同)