How can I validate the range 1-99 using a regex?

后端 未结 11 1270
忘掉有多难
忘掉有多难 2021-02-07 03:00

I need to validate some user input, to ensure a number entered is in the range of 1-99 inclusive. These must be whole (Integer) values

Preceeding 0 is permitted, but opt

相关标签:
11条回答
  • 2021-02-07 03:56

    I think it should be like...

    ^(0[1-9]|[1-9][0-9])$
    
    0 讨论(0)
  • 2021-02-07 03:57
    String d = "11"
    
    if (d.length() <= 2 && d.length() >=1) {
        try {
            Integer i = Integer.valueOf(d);
            return i <= 99 && i >= 0
        }
        catch (NumberFormatException e) {
            return false;
        }
    }
    
    0 讨论(0)
  • 2021-02-07 03:58

    pretty late but this will work.

    ^[1-9][0-9]?$
    
    0 讨论(0)
  • 2021-02-07 04:00

    Why is regex a requirement? It is not ideal for numeric range calculations.

    Apache commons has IntegerValidator with the following:

    isInRange(value, 1, 99)
    

    In addition, if you're using Spring, Struts, Wicket, Hibernate, etc., you already have access to a range validator. Don't reinvent the wheel with Regular Expressions.

    0 讨论(0)
  • 2021-02-07 04:03

    This is the simplest possible, I can think of:

    ^([1-9][0-9]?)$

    Allows only 1-99 both inclusive.

    0 讨论(0)
提交回复
热议问题