Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx Numeric Check in Range?

Tags:

regex

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!

like image 874
Blake Blackwell Avatar asked Mar 25 '09 12:03

Blake Blackwell


People also ask

How do you find the range of a number in regex?

To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets. For example, [A-CX-Z] matches 'A' or 'B' or 'C' or 'X' or 'Y' or 'Z'.

What is the regular expression for numbers only?

To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.

What does D in regex mean?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).

Why * is used in regex?

* - means "0 or more instances of the preceding regex token"


1 Answers

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
like image 75
JaredPar Avatar answered Sep 20 '22 18:09

JaredPar