-2

I'm using replaceAll() to remove all the "00" from the given String. Though it's removing all the 00, it is also removing a preceding character.

String a = "2400.00";
String a1 = a.replaceAll(".00", "");

I expected 24 as o/p but got 2.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
UTKAL
  • 1
  • 1
  • 3
    Because [`String.replaceAll`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-) accept a regex. `"."` means any character. I vote to close since this is just a typo. – AxelH Apr 16 '19 at 05:43
  • 1
    Why whould you expect 24 from 2400.00 by removing .00 ? – Antoniossss Apr 16 '19 at 05:45
  • I think replace takes the number of occurrences you can give how many char you want your replace replace all will replace all the char as it takes regex and . Means everything – Raman Mishra Apr 16 '19 at 05:45
  • So, if you remove _all the "00" form the given String_, you would get `"24."` but you expect `"24"`. What is exactly your expectation here ? – AxelH Apr 16 '19 at 05:50
  • If you want to match the trailing zeroes and the following dot with 2 zeroes for decimal values try `(?<!\S)(\d+?)0*\.00(?!\S)` [demo](https://regex101.com/r/qsh0V6/1) and replace with the first capturing group `$1` – The fourth bird Apr 16 '19 at 06:25

3 Answers3

4

The . means any character in regex. replaceAll uses a regex as arugment. Please escape it. a.replaceAll("\\.00", "");

Or just simply use replace(".00", "").

cmoetzing
  • 742
  • 3
  • 16
  • why would not use `replace` instead ? – Scary Wombat Apr 16 '19 at 05:46
  • 1
    If he is expecting more then on possible occurance `replaceAll` is the right choice. If you know it is only present once you can use `replace` – cmoetzing Apr 16 '19 at 05:49
  • 2
    That is incorrect, `replace` Also replaces ALL occurrences - as per javadocs *Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.* – Scary Wombat Apr 16 '19 at 05:57
  • @ScaryWombat You are right. `replace` would be easier indeed. – cmoetzing Apr 16 '19 at 06:01
2

replaceAll takes regex as first argument. In regex sytax .(dot) means ANY character, thus the result.

Either escape that dot with \\ or use replace instead of replaceAll (replace still replaces all occurences, but argument is "pattern" to replace, not regex)

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

This is because . cmatches any character in regex (well, except for the newline character, but it can be changed with appropriate flag).

That's why it matches 400 as well as .00 and replaces it.

What you need is to replace 00 or .00, so you need pattern: \.?00

Explanation:

\.? - match . zero or one time

00 - match 00 literally

Demo

Code:

String a = "2400.00";
String a1 = a.replaceAll("\\.?00", "");
System.out.println(a1);
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69