user3580890
user3580890

Reputation: 191

How to replace a String starting with $ character using Java's String.replaceAll method

What's the correct regex for a String starting with $ char as the first argument (i.e. the string to replace) to Java's replaceAll method in the String class? I can't get the syntax right. Example

String s = "SUMIF($C$6:$C$475,\"   India - Hyd\",K$6:K$475)";
System.out.println(s.replaceAll("$475", "$44"));

Upvotes: 2

Views: 1978

Answers (3)

Naman Gala
Naman Gala

Reputation: 4692

Documentation of string.replace() states that

public String replace(CharSequence target, CharSequence replacement)

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

So you can use replace method instead of replaceAll.

String s = "SUMIF($C$6:$C$475,\"   India - Hyd\",K$6:K$475)";
System.out.println(s.replace("$475", "$44"));

Upvotes: 1

shmosel
shmosel

Reputation: 50716

I would suggest in this case you use replace() instead of replaceAll(), because you're not using any regex:

System.out.println(s.replace("$475", "$44"));

Upvotes: 7

Jens
Jens

Reputation: 69440

This should work:

System.out.println(s.replaceAll("\\$475", "\\$44"));

Upvotes: 4

Related Questions