tags:

views:

754

answers:

5

Hi! 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!

+8  A: 

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
JaredPar
@ybo, yes it will. But they said they wanted 06 so i assumed 00 was also valid.
JaredPar
@Jared, I removed my comment after your edit, but I still understand that he needs values between 1 and 50. 0 and 00 should be excluded, I think.
ybo
@ybo, you're correct. I updated the answer to exclude all forms of 0
JaredPar
This works perfectly. I did need to exclude 00, so this looks like it took care of it. This site is awesome! I appreciate everyone's help!
Blake Blackwell
I think it should be ^0*([1-9])|([1-4][0-9])|(50)$, considering that 006 = 06 = 6, a number within the mathematical range [1,50], and similarly for 050. Or (faster I think) ^0*([1-4][0-9]?)|(50?)|([6-9])$
MSalters
+4  A: 

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.

Doug
+1  A: 

This related question might be helpful: How to match numbers between X and Y with regexp?

Tomalak
+1  A: 

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.

S.Lott
A: 

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

Brijesh Mishra