1

I want to remove leading 0s from my decimal string.

I'm using right now below code snippet.

inp.replaceAll("^0*","")

Its working fine until am getting 0.00. Becasue if 0.00, Its giving me .00 as output, which is not correct ..!

Can anyone share how it can achieved using regex ?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Elena
  • 181
  • 1
  • 11
  • The `0.` at the start of `0.00` is not matched with `^0+(?!\.0+$)` because `(?!\.0+$)` does not allow matching `0` that is followed with `.` and 1 or more zeros. See [my answer](https://stackoverflow.com/a/56457560/3832970). I explained every part of the regex. – Wiktor Stribiżew Jun 05 '19 at 09:28
  • If you have trouble understanding how negative lookahead works, please see [here](https://stackoverflow.com/a/31201710/3832970) and [here](https://stackoverflow.com/questions/32886477/regexp-find-numbers-in-a-string-in-any-order/32886855#32886855), my former answers where I explained their workings in detail. – Wiktor Stribiżew Jun 05 '19 at 11:00

2 Answers2

0

You may use

s = s.replaceAll("^0+(?!\\.0+$)", "");

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • 0+ - one or more 0 digits
  • (?!\\.0+$) - not immediately followed with . and 1+ zeros up to the end of the string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    it’s not working...If I use 00.7700 it’s showing .7700...Not correct ....! – Elena Jun 12 '19 at 11:28
  • @Elena Then use `"^0+(?!\\.)"` or `"^0+(?=[^.])"`. Could you please collect your test cases and add them to the question? It will be easier to give you the definitive answer. – Wiktor Stribiżew Jun 12 '19 at 11:40
0
@Test
public void testStripLeadingZero() {
    List<String> tests = new ArrayList<>(Arrays.asList(
            "0.05",
            "-0.03",
            "100.03",
            "-100.03",
            "000010",
            "-00020",
            "0077.778",
            "-0088.888"
    ));
    for (String s : tests) {
        String result = s.replaceFirst("^0+", "").replaceFirst("^-0+", "-");
        System.err.println("result: " + result);
    }
}

Output:

result: .05
result: -.03
result: 100.03
result: -100.03
result: 10
result: -20
result: 77.778
result: -88.888
user3892260
  • 965
  • 2
  • 10
  • 19