Blake Blackwell
Blake Blackwell

Reputation: 7795

RegEx Numeric Check in Range?

I'm new to StackOverflow, so please let me know if there is a better way to ask the following question.

I need to create a regular expression that detects whether a field in the database is numeric, and if it is numeric does it fall within a valid range (i.e. 1-50). I've tried [1-50], which works except for the instances where a single digit number is preceded by a 0 (i.e. 06). 06 should still be considered a valid number, since I can later convert that to a number.

I really appreciate your help! I'm trying to learn more about regular expressions, and have been learning all I can from: www.regular-expressions.info. If you guys have recommendations of other sites to bone up on this stuff I would appreciate it!

Upvotes: 13

Views: 22987

Answers (4)

Brijesh Mishra
Brijesh Mishra

Reputation: 2748

^0?[1-50]{1,2}$

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

Try this

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

The idea of this regex is to break the problem down into cases

  • 0?[1-9] takes care of the single digit case allowing for an optional preceeding 0
  • [1-4][0-9] takes care of all numbers from 10 to 49. This also allwows for a preceeding 0 on a single digit
  • 50 takes care of 50

Upvotes: 17

S.Lott
S.Lott

Reputation: 391852

You can't easily do range checking with regular expressions. You can -- with some work -- develop a pattern that recognizes a numeric range, but it's usually quite complex, and difficult to modify for a slightly different range.

You're better off breaking this into two parts.

  1. Recognize the number pattern (^\d+$).

  2. Check the range of that number in an application program.

Upvotes: 2

Doug
Doug

Reputation: 9100

Regular expressions work on characters (in this case digits), not numbers. You need to have a separate pattern for each number of digits in your pattern, and combine them with | (the OR operator) like the other answers have suggested. However, consider just checking if the text is numeric with a regular expression (like [0-9]+) and then converting to an integer and checking the integer is within range.

Upvotes: 5

Related Questions