0

I have a "balance" string which contain a dollar sign in front of it. I would like to amend this sign, so I can convert the sting to double, but my code isn't working.

Here is what I've tried:

String balance = "$5.30";
balance = balance.replaceFirst("$", "");

It looks like the code doesn't make any difference. To make it even more weird, the code below does exactly what I need:

String balance = "$5.30";
balance = balance.replaceFirst(".", "");

Even though I could of just use the 2nd code, I want to understand why does it lead to this result.

Allan Spreys
  • 5,287
  • 5
  • 39
  • 44

1 Answers1

7

$ and . are a special characters(meta character) in java regex world, you should escape it with backslash in order to treat it as a normal charecter.

String balance = "$5.30";
balance = balance.replaceFirst("\\$", "");

String balance = "$5.30";
balance = balance.replaceFirst("\\.", "");

Thus :

      String balance = "$5.30";
      balance = balance.replaceFirst("\\.", "").replaceFirst("\\$", "");
      System.out.println(balance);

Output: 530

Just wanted to add more explanation about $and . meaning in regex:

  1. $ is used to check if line end follows
  2. . is used to match any sign

here's a tutorial for Regex in java

PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • The [documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst%28java.lang.String,%20java.lang.String%29) is crystal clear: *"Replaces the first substring of this string that matches the given **regular expression** with the given replacement."* – Mattias Buelens Dec 23 '12 at 00:05
  • @VladSpreys please dont just copy it, read about regex in oracle java trails its pretty good for basic regex. and also it'd g8 if you'd accept the answer :) – PermGenError Dec 23 '12 at 00:10
  • I sure will, I can't accept the answer just yet (system limitation), but will within 5 minutes – Allan Spreys Dec 23 '12 at 00:12