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

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

This question is related to regex numbers

The answer is


Just add a 0 or 1 token:

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

^(-?\d+\.)?-?\d+$

allow:

23425.23425
10.10
100
0
0.00
-100
-10.10
10.-10
-10.-10
-23425.23425
-23425.-23425
0.234

This will allow a - or + character only when followed by a number:

 ^([+-](?=\.?\d))?(\d+)?(\.\d+)?$

For negative number only, this is perfect.

^-\d*\.?\d+$

Some Regular expression examples:

Positive Integers:

^\d+$

Negative Integers:

^-\d+$

Integer:

^-?\d+$

Positive Number:

^\d*\.?\d+$

Negative Number:

^-\d*\.?\d+$

Positive Number or Negative Number:

^-?\d*\.{0,1}\d+$

Phone number:

^\+?[\d\s]{3,}$

Phone with code:

^\+?[\d\s]+\(?[\d\s]{10,}$

Year 1900-2099:

^(19|20)[\d]{2,2}$

Date (dd mm yyyy, d/m/yyyy, etc.):

^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$

IP v4:

^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$

^[+-]?\d{1,18}(\.\d{1,2})?$

accepts positive or negative decimal values.


Regular expression for number, optional decimal point, optional negative:

^-?(\d*\.)?\d+$;

works for negative integer, decimal, negative with decimal


I don't know why you need that first [0-9].

Try:

^-?\d*(\.\d+)?$

Update

If you want to be sure that you'll have a digit on the ones place, then use

^-?\d+(\.\d+)?$

UPDATED(13/08/2014): This is the best code for positive and negative numbers =)

(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}

I tried with this numbers and works fine:

-1234454.3435
-98.99
-12.9
-12.34
-10.001
-3
-0.001
-000
-0.00
0
0.00
00000001.1
0.01
1201.0000001
1234454.3435
7638.98701

I have some experiments about regex in django url, which required from negative to positive numbers

^(?P<pid>(\-\d+|\d+))$

Let's we focused on this (\-\d+|\d+) part and ignoring others, this semicolon | means OR in regex, then the negative value will match with this \-\d+ part, and positive value into this \d+


This worked for me, allowing both negative and positive numbers:

 \-*\d+

If using C#:

Regex.Match(someString, @"\-*\d+").Value;

This will allow both positive and negative integers

ValidationExpression="^-?[0-9]\d*(\d+)?$"


If you have this val="-12XXX.0abc23" and you want to extract only the decimal number, in this case this regex (^-?[0-9]\d*(\.\d+)?$) will not help you to achieve it.
this is the proper code with the correct detection regex:

_x000D_
_x000D_
var val="-12XXX.0abc23";_x000D_
val = val.replace(/^\.|[^-?\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');_x000D_
console.log(val);
_x000D_
_x000D_
_x000D_