ReplaceAll () string in java

Can you explain the conclusion

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

What is the conclusion? This excludes

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

By removing $ his work. Why?

+4
source share
5 answers

Because $ is a special regular expression character. If you want to use it with such a normal character.

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

String.replaceAll() accepts a regular expression .

And $ in regex is used to replace captured groups. How $1 represents the contents of the first captured group ... etc.

In your case, since you are not using a regular expression, just use String.replace("AMOUNT", amount)

+12
source

$ is a special char in the regular expression. You can avoid this by using \\

  String amount = "\\$10.00"; 
+4
source

you need to write it as

 String amount = "\\$10.00"; 
0
source

When $ is provided, it accepts it as a regular expression, but actually it is not.

-3
source

All Articles