How do I include negative decimal numbers in this regular expression?

user1786107 picture user1786107 · Apr 4, 2013 · Viewed 171.7k times · Source

How do I match negative numbers as well by this regular expression? This regex works fine with positive values, but I want it to also allow negative values e.g. -10, -125.5 etc.

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

Thanks

Answer

Mike Perrenoud picture Mike Perrenoud · Apr 4, 2013

You should add an optional hyphen at the beginning by adding -? (? is a quantifier meaning one or zero occurrences):

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

I verified it in Rubular with these values:

10.00
-10.00

and both matched as expected.