1

I've tried built-in method String#replaceAll() to replace all "$" from my String content. But it's not working.

String ss = "HELLO_$_JAVA";
System.out.println(ss.indexOf("$"));
System.out.println(ss);
ss = ss.replaceAll("$", "");
System.out.println(ss);// 'HELLO__JAVA' is expected

OUTPUT:

6
HELLO_$_JAVA
HELLO_$_JAVA

Expected output:

6
HELLO_$_JAVA
HELLO__JAVA

EDIT: Although Java regular expressions and dollar sign covers the answer, but still my question may be helpful for someone who is facing same problem when using String#replaceAll(). And Difference between String replace() and replaceAll() also may be helpful.

Two possible solution of that question is

ss = ss.replace("$", "");

OR

ss = ss.replaceAll("\\$", "");
Community
  • 1
  • 1
mmuzahid
  • 2,252
  • 23
  • 42

3 Answers3

9

The first parameter of the replaceAll method takes a regular expression, not a literal string, and $ has a special meaning in regular expressions.

You need to escape the $ by putting a backslash in front of it; and the backslash needs to be double because it has a special meaning in Java string literals.

ss = ss.replaceAll("\\$", "");
Jesper
  • 202,709
  • 46
  • 318
  • 350
8

String.replaceAll is for regular expressions. '$' is a special character in regular expressions.

If you are not trying to use regular expressions, use String.replace, NOT String.replaceAll.

khelwood
  • 55,782
  • 14
  • 81
  • 108
-1

May be not the best way but a work around,

String parts[] = ss.split("\\$");

Then concat each of them

String output = "";
for(String each:parts){
    output=output+each;
}

Then you have your replaced string in output

Nabin
  • 11,216
  • 8
  • 63
  • 98