I like this regexp for floating point numbers, its pretty smart in that it wont match 0.0
as a number. It requires at least one non-zero number on either side of the period. Figured I'd break it into its parts to provide a deeper understanding of it.
^ #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 regexp has two smaller patterns inside of it, the first matches cases where the number is >= 1 (having at least one non-zero character left of the .) optionally allowing for a period with one or more trailing 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 the [0]*
solution to the problem.
Couple of regexp shortcuts, you could replace any instance of [0-9]
with \d
in most regexp flavors. Also [0]
only matches 0
so you might as well just use 0*
instead of [0]*
. The final regexp:
/^(\d*[1-9]\d*(\.\d+)?|0*\.\d*[1-9]\d*)$/