Regular expression to match decimal places with or without leading zeros
I love this regex for floating point numbers, its pretty smart as it doesn't match 0.0
as a number. This requires at least one non-zero number on either side of the period. I realized that I would have broken it into pieces in order to understand it more deeply.
^ #Match at start of string
( #start capture group
[0-9]* # 0-9, zero or more times
[1-9] # 1-9
[0-9]* # 0-9, zero or more times
( #start capture group
\. # literal .
[0-9]+ # 0-9, one or more times
)? #end group - make it optional
| #OR - If the first option didn't match, try alternate
[0]+ # 0, one or more times ( change this to 0* for zero or more times )
\. # literal .
[0-9]* # 0-9, zero or more times
[1-9] # 1-9
[0-9]* # 0-9, zero or more times
) #end capture group
$ #match end of string
The regex has two small patterns in it, the first matches cases where a number> = 1 (having at least one non-zero character to the left of.), Optionally allowing a period with one or more finite numbers. The second matches 1.0 and ensures that there is at least one non-zero digit on the right side of the dot.
Johannes' answer already gives you a solution to the problem [0]*
.
A couple of regexp shortcuts, you can replace any instance [0-9]
with \d
in most regexp variants. Also [0]
matches only 0
, so you can just use 0*
instead [0]*
. Last regex:
/^(\d*[1-9]\d*(\.\d+)?|0*\.\d*[1-9]\d*)$/
source to share