Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Regular Expression for Number Range

Tags:

c#

regex

asp.net

I'm trying to build up some regular expressions to validate some textbox controls. I have done some research and testing but cannot get this one working. Examples of what i am trying to create regular expressions for are as follows:

  1. Range 0-45, 0 decimal places
  2. Range 0-20, 2 decimal places
  3. Range 16-65, 0 decimal places
  4. Range 0-99, 2 decimal places
  5. Range 0-1500000, 0 decimal places
  6. Range 0-200, 1 decimal place

For 1 and 5 respectively, I have used

([0-9]|[0-9]\d|45)$  
([0-9]|[0-9]\d|1500000)$  

The first one I am having problems for is an age range of 16-65 (inclusive), where I want no decimal places. After a post on here (Regular expression to allow numbers between -90.0 and +90.0) I thought I could use the logic and get it sussed, but can't!

The expression I got to was:

(\d|([1-6][6-4]))|65  

Can someone please tell me where I'm misunderstanding this! And any help with the other examples above would be gratefuly received.

like image 387
Martin S Avatar asked Jan 26 '11 15:01

Martin S


1 Answers

Sorry to say this, but none of your regexes are going to work. Remember that regular expressions are designed to match textual data. While it's possible to use them to match numbers, it's not really the tool of choice.

If you have to use a regex, you need to think of the possible textual representations of a number range.

For your example 1, that would be:

  1. either a single digit
  2. or a digit between 1 and 3, followed by any digit
  3. or a 4, followed by a digit between 0 and 5.

As a regex:

^(?:\d|[1-3]\d|4[0-5])$

The ^ and $ anchors make sure that the entire string is evaluated; the (?:...) groups the alternation and "shields" it from the anchors.

For your example 3:

  1. either a 1, followed by 6-9
  2. or a 2-5, followed by any digit
  3. or a 6, followed by 0-5

As a regex:

^(?:1[6-9]|[2-5]\d|6[0-5])$

For your example 5:

  1. 1-5 digits
  2. or a 1, followed by 0-4, followed by any four digits
  3. or 150000.

As a regex:

^(?:\d{1,5}|1[0-4]\d{4}|150000)$

And so on.

Adding decimal places is not very difficult:

  • \.\d{2} works for exactly two decimal places
  • \.\d{1,3} for 1 to 3 decimal places
  • and (?:\.\d{1,2}) for 0 to 2 decimal places (and the dot is only allowed if at least one digit follows).
like image 130
Tim Pietzcker Avatar answered Oct 11 '22 15:10

Tim Pietzcker