Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

numbers

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

like image 284
user1786107 Avatar asked Apr 04 '13 14:04

user1786107


People also ask

How do you do decimal numbers in regular expressions?

A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.

Does decimal allow negative number?

If UNSIGNED is used with DECIMAL , negative values are not allowed. MySQL stores numbers in DECIMAL columns as strings. Therefore, numbers outside the maximum numeric range for this data type may be stored in a DECIMAL column.

Can decimal in SQL be negative?

The decimal datatype can store negative numbers as well. So to answer your question, yes you can use the decimal datatype to store negative decimal numbers.


1 Answers

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.

let r = new RegExp(/^-?[0-9]\d*(\.\d+)?$/);  //true console.log(r.test('10')); console.log(r.test('10.0')); console.log(r.test('-10')); console.log(r.test('-10.0')); //false console.log(r.test('--10')); console.log(r.test('10-')); console.log(r.test('1-0')); console.log(r.test('10.-')); console.log(r.test('10..0')); console.log(r.test('10.0.1'));
like image 114
Mike Perrenoud Avatar answered Oct 14 '22 03:10

Mike Perrenoud