开发者

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

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 optional

Valid values

  1. 1
  2. 01
  3. 10
  4. 99
  5. 09

Invalid values

  1. 0
  2. 007
  3. 100
  4. 10.5
  5. 010

So far I have the following regex that I've worked out : ^0?([1-9][0-9])$

This allows an optional 0 at the beginning, but isn't 100% correct as 1 is not deemed as valid

An开发者_JAVA技巧y improvements/suggestions?


Off the top of my head (not validated)

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


Here you go:

^(\d?[1-9]|[1-9]0)$

Meaning that you allow either of

  1. 1 to 9 or 01 to 09, 11 to 19, 21 to 29, ..., 91 to 99
  2. 10, 20, ..., 90


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

should work


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.


pretty late but this will work.

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


I think it should be like...

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


This one worked for myself:

([1-9][0-9])|(0?[1-9])

It checks for 10-99 or 1-9 => 1-99 with one leading zero allowed


Just do:

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

The range will be set from 0 to 9 and the {1,2} means min digits = 1 and max digits = 2.

It will accept, for example: 0, 00, 01, 11, 45, 99, etc... It will not accept, for example: 000, 1.2, 5,4, 3490, etc...


This is the simplest possible, I can think of:

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

Allows only 1-99 both inclusive.


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

should work too (it'll will match 00 too, hope it's a valid match).


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜