0

I am looking for a regex that would normalize decimal number. When I say normalize I mean remove all leading zeros, and all trailing zeros after decimal point.

For example:

0.0 -> 0
1.230 -> 1.23
00123 -> 123
012.30400 -> 12.304
0102 --> 102"

So far i have came up with this

(?<=,|^)(?:[0.+-]+(?=0(?:,|.\B|$))|0+(?=[1-9]))|.0+\b|\b0+(?=\d*.\b)|.\B|(?<=[1-9])0+(?=,|$)

the only problem for 0.1 it returns .1 otherwise it works

  • See a possible solution [here](http://stackoverflow.com/a/35351336/3832970). – Wiktor Stribiżew Feb 03 '17 at 16:02
  • `[1-9]\d*(\.\d*[1-9])?` [nearly works](https://regex101.com/r/nSwepA/1), but fails for `0.x`. – Aaron Feb 03 '17 at 16:06
  • "When I say normalize I mean remove all leading zeros" and "the only problem for 0.1 it returns .1" are contradictory. You *specifically* request to remove all leading zeros, and then point out as a problem that a leading zero is removed. One answer you got would cause this leading zero to be removed, the other would not, so this did in fact cause unnecessary confusion. –  Feb 03 '17 at 17:55

2 Answers2

0

If it's one entry per line, try

^0*(\d+(?:\.(?:(?!0+$)\d)+)?)

See it here at regex101.

If you want to scan all for all, you could try

\b0*(\d+(?:\.(?:(?!0+\b)\d)+)?)

See it here at regex101.

They both captures the number(s) to group 1.

If you want to remove everything but numbers, replace

^0*(\d+(?:\.(?:(?!0+$)\d)+)?).*$

with group 1.

Check it out here.

SamWhan
  • 8,296
  • 1
  • 18
  • 45
0

A simple alternation should suffice:

^0+|(\.[0-9]+)0+$

Replacement would be capture group 1.

Kenneth K.
  • 2,987
  • 1
  • 23
  • 30