0

I have code that does't like dollar sign that must be vissible in replacement.

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

I have exception java.lang.IllegalArgumentException: Illegal group reference

I expet to get string "this is amount $2.60 you must pay"

How to change my code to have required result?

6 Answers 6

5

If you don't need to use regular expressions (you don't seem to), use replace instead:

s1 = s1.replace("<AMOUNT>", "$2.60");
Sign up to request clarification or add additional context in comments.

6 Comments

what if I want to replace with regular expressions.?
@SaurabhAgarwal Then use replaceAll and escape special characters, but there is no need for a regex in your example.
Yes in this example it's not requires. I asked just for the sake of my knowledge.
@SaurabhAgarwal If you look at the javadoc of the various String methods, those that use regular expressions generally take a String regex argument, like split, matches and replaceAll for example.
@SaurabhAgarwal And the detail of regex patterns in Java can be found in the Pattern javadoc
|
3

You have to change your code like this:

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

1) escape $ character

2) you need to save the result of replaceAll method, so assign it to s1 again.

Comments

2

Just use replace instead. No need to use regular expression.

s1 = s1.replace("<AMOUNT>", "$2.60");

1 Comment

Don't forget to reassign s1! :)
0

Regular expressions use the special character $ to indicate a group in the expression. That's why you got confused. If you want the literal thing, just escape it.

public static void main(String[] args) {  
    String s1= "this is amount <AMOUNT> you must pay";
    System.out.print(s1.replaceAll("<AMOUNT>", "\\$2.60"));
}     

Comments

0

When not using regex, you should use replace().

Also you should store the resulting string somewhere else, like

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

Comments

0

use double slash \\ before $ symbol.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.