Forteasics
Forteasics

Reputation: 121

Regex for number check below a value (12)

I need to validate a number input to two characters and it can't be more than the value 12.

The two numbers easy:

/^\d{1,2}$/

Then check that if there are two numbers then the first must be either 0 or 1, and the second must be either 0, 1, or 2. That part I don't know how to express, regularly...

And also if possible I would like to have it in single regex statement.

Upvotes: 6

Views: 17704

Answers (6)

daniel-sc
daniel-sc

Reputation: 1307

The following code (Groovy) creates a regex similar to the answer from @Gery Green but works for any given number:

String getSmallerNumberRegEx(String number) {
  int length = number.length()
  List<String> patterns = [];
  if (length >= 2) {
    patterns.add("\\d{1,${length - 1}}") // any number with less digits
  }
  for (int i = 0; i < number.length(); i++) {
    def digit = number[i].toInteger()
    if (digit > 0) {
      // same prefix + smaller number + any postfix:
      patterns.add("${number.substring(0, i)}[0-${digit - 1}]\\d{${length - i - 1}}")
    }
  }
  return patterns.join('|')
}

Upvotes: 0

falopsy
falopsy

Reputation: 636

0[0-9]|1[0-2]

Description:

 [0-9] : number between 00 and 09
     | : or
1[0-2] : and if starting with 1, next number should be between 0 -1 (testing 10-12)

Upvotes: 0

Gary Green
Gary Green

Reputation: 22395

Regex is not suited to dealing with ranges like this, but anyway this should work:

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

Description:

^       match start of the string
(0?     optional zero
[1-9]       any number between 1 and 9
|1[012])    or match 1 followed by either a 0, 1, 2 i.e. 10, 11, 12.
$           match end of string

Upvotes: 15

Frank Schmitt
Frank Schmitt

Reputation: 30835

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

this matches a zero, followed by one arbitrary digit, or a one, followed by 0, 1 or 2

Upvotes: 0

Piskvor left the building
Piskvor left the building

Reputation: 92792

For the "character either x, or y, or z, or ...", there's the character class, expressed in square brackets:

[012]

means "any character of 0,1, or 2".

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401172

For something like this (testing if an integer is less than a given value), you should really not use a regex.

Instead, just use a simple condition like this one (the syntax will depend on the language you're working with) :

if ($variable <= 12) {
  // OK
}
else {
  // Not OK
}

Upvotes: 1

Related Questions