简体   繁体   中英

Java. Strange behaviour of string.replaceFirst()

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.

$ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM