Regex to truncate trailing zeroes

前端 未结 2 2090
情歌与酒
情歌与酒 2021-01-22 15:45

I\'m trying to construct a single regex (for Java) to truncate trailing zeros past the decimal point. e.g.

  • 50.000 → 50
  • 50.500 → 50.5
  • 50.0500 → 5
2条回答
  •  感动是毒
    2021-01-22 16:35

    For a general regex which should do the trick:

    ^\d+?0*\.??\d*?(?=0*?[^\d]*$)

    You can replace the caret and dollar sign with whatever your boundaries should be. Those could be replaced by whatever you would expect around your number.

    basically:

    /d+? non-greedy match for any number (needs at least 1 number to start the match)

    \.*?? optional match for a decimal. Prefers to match 0 occurrences

    \d*? (?=0*?[^\d]*$) - non-greedy match for a number, but would stop at the 0 which is proceeded by a non-number

    EDIT: I just realized the original expression also trimmed the last zero on integers, this should work. I added the option 0 match to catch that

提交回复
热议问题