Regex for numeric range from negative numbers?

前端 未结 6 1977
忘掉有多难
忘掉有多难 2021-02-13 19:34

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 he

相关标签:
6条回答
  • 2021-02-13 20:06

    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*)?$
    
    0 讨论(0)
  • 2021-02-13 20:13

    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.

    0 讨论(0)
  • 2021-02-13 20:14

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

    (\d+|-\d+)
    
    0 讨论(0)
  • 2021-02-13 20:16

    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

    0 讨论(0)
  • 2021-02-13 20:21

    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.

    0 讨论(0)
  • 2021-02-13 20:22

    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*$/
    
    0 讨论(0)
提交回复
热议问题