views:

239

answers:

7

Hi,

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

Any improvements/suggestions?

+7  A: 

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
Alin Purcaru
It looks like no one else thinks backwards :)
Alin Purcaru
+12  A: 

Off the top of my head (not validated)

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

developmentalinsanity
I think this should be: `^(0?[1-9]|[1-9][0-9])$`. Otherwise, the ^ is bound only to the first alternative, and the $ to the second. Then again, I don't specifically know Java regexes.
Jander
Hence the "not validated". I couldn't remember that sort of thing specifically.
developmentalinsanity
note: ^ and $ are not needed if using the `Matcher.matches()` method, since it attempts to match the whole string...
Carlos Heuberger
+3  A: 
^(([0-9][1-9])|([1-9][0-9])|[1-9])$

should work

red-X
A: 

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;
}
}
Gadolin
You did read the part about the RegExp, right?
st0le
I did not find it as an requirement in description, though now I see it in title. It seemed funny to go out from regex and have same thing.
Gadolin
A: 

^[0-9]{1,2}$ should work too (it'll will match 00 too, hope it's a valid match).

Lalith
`00` is NOT in the range 1-99 as required... and it will also match `0`, which is listed as invalid.
Carlos Heuberger
+1  A: 

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.

Mark Thomas
A: 

I might miss the point, but why not use ^\d?\d$ ?

svenor
@svenor: Unfortunately the range is 1-99, and this regex accepts 0 and 00.
indiv
I knew that I missed something...
svenor
Second attempt: ^(0?[1-9]|[1-9]\d)$ ... which is basically the same as the winning answer given by developmentalinsanity
svenor