Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replaceAll() in java [duplicate]

Tags:

java

Can you explain the output

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

What is the output? It throws exception

Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1

By removing $ its working.Why?

like image 504
Monisha Avatar asked Dec 11 '22 21:12

Monisha


2 Answers

String.replaceAll() accepts a regex.

And $ in regex are used for replacing the captured groups. Like $1 represent's the content of first captured group... and so on.

In your case, since you don't use regex at all just use String.replace("AMOUNT", amount)

like image 107
Codebender Avatar answered Dec 28 '22 15:12

Codebender


$is a special char in regex. You can escape it by using \\

      String amount = "\\$10.00";
like image 43
Jens Avatar answered Dec 28 '22 14:12

Jens