jon kra
jon kra

Reputation: 143

Regex for numeric range from negative numbers?

I want to validate a number using regex.. the condition is number can be from any negative 3 digit values to positive 3 digit.. but cannot be zero.

can someone please help me to get regex condition for this.

Upvotes: 14

Views: 50528

Answers (6)

Shachi
Shachi

Reputation: 1888

What worked for me as the best is:

^[+-]?[0-9]*$

I was checking regex datatype and the range of positive and negative number.

This solution worked.

Upvotes: 0

user2074102
user2074102

Reputation:

I used this with the .NET System.Text.RegularExpressions to match positive or negative decimals (numbers).

(\d+|-\d+)

Upvotes: 1

pcofre
pcofre

Reputation: 4066

There it´s It can or not start with the negative symbol, followed by a number between 1 and 9 ant then can be 0 to 2 of any number.

^\-?[1-9]\d{0,2}$

Update: And the following regex also allows decimals

^\-?[1-9]\d{0,2}(\.\d*)?$

Upvotes: 18

user666
user666

Reputation: 1172

I think in all the above input like this is allowed -2-22,2-22 which is a minor bug.Review this as well :-

[\-]?[0-9]*$/

even smaller :

/^[\-]?\d*$/

Upvotes: 0

Aditya Kresna Permana
Aditya Kresna Permana

Reputation: 12099

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 if we got negative value it will be matched with this \-\d+ part, and positive value into this \d+ part

Upvotes: 0

xkrz
xkrz

Reputation: 166

Assuming you are dealing with whole integers, and your number don't mix with other texts, you can try this

^-?[1-9][0-9]{0,2}$

I agree with Anon, it is much better to read the String, and convert it to int to do the comparison, if you have predictable inputs.

Upvotes: 3

Related Questions