om39a
om39a

Reputation: 1406

Solving a Regex for a number range

I am in need of a regfex for a validation framework which accepts regex formats for validation. I cannot use arithmetic and comparative operators. I have come up with a solution but It is not working as expected. I want to know what’s wrong with the regex which I came up with and how to sort it out right

Regex for any number from 10429 to 40999

My solution:

^1042[9-9]|104[3-9][0-9]|10[5-9][0-9][0-9]|1[1-9][0-9][0-9][0-9][0-9]|[2-3][0-9][0-9][0-9][0-9]|40[0-9][0-9][0-9]

But this one is not working.

Upvotes: 2

Views: 5335

Answers (6)

Vik
Vik

Reputation: 91

try this - \b(10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{3}|[23][0-9]{4}|40[0-9]{3})\b

Upvotes: 0

Justin Morgan
Justin Morgan

Reputation: 30700

I'm seeing some very long regexes here. This task can be solved without a lot of redundancy in your pattern. If you don't have anything other than regex to work with, here's the pattern you want:

^(([123][1-9]|[234]0)[0-9]{3}|10([5-9][0-9]{2}|4([3-9][0-9]|29)))$

Here it is expanded to show you what it means:

 ^                      #The beginning of the line. This ensures 10429 passes, but 9999910429 doesn't.
 (                      
   ([123][1-9]|[234]0)  #This lets the first two digits be anything from 11-40. We'll deal with 10xxx later on.
   [0-9]{3}             #If the first two digits are 11-40, then the last three can be anything from 000-999. 
 |                      
   10                   #Okay, we've covered 11000-40999. Now for 10429-10999.
   (
     [5-9][0-9]{2}      #Now we've covered 10500-10999; on to the 104xx range.
   |
     4                  
     (
        [3-9][0-9]      #Covers 10430-10499.
     |
        29              #Finally, the special case of 10429.
     )
   )                  
 )
 $                      #The end of the line. This ensures 10429 passes, but 104299999 doesn't.

If the numbers aren't the entire input, but rather embedded in a string (e.g. you want to get all the numbers from the string "blah blah 11000 foo 39256 bar 22222", replace both ^ and $ with \b.

See it working on Regexr: http://regexr.com?312p0

Upvotes: 0

Darshana
Darshana

Reputation: 2548

try this ^(10429|104[3-9]\d|10[5-9]\d{2}|1[1-9]\d{3}|[2-3]\d{4}|40\d{3})$

Upvotes: 0

Cylian
Cylian

Reputation: 11181

Try this

^(10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{3}|[23][0-9]{4}|40[0-9]{3})$

For generating pattern number Ranges visit here.


Hope this helps.

Upvotes: 9

Russell Dias
Russell Dias

Reputation: 73392

10429|104[3-9][0-9]|10[5-9][0-9]{2}|1[1-9][0-9]{3}|[23][0-9]{4}|40[0-9]{3} should do the trick.

Although why you would need this is beyond me...

Upvotes: 0

Kobi
Kobi

Reputation: 138147

  1. 1[1-9][0-9][0-9][0-9][0-9] - too many digits.
  2. ^1|2|3 actually means (?:^1)|2|3 - you need ^(?:10429|...|40[0-9][0-9][0-9])$.

Upvotes: 4

Related Questions