0

I am just a beginner in python and I am using regex to find a number between 540-600

and have written following script but this doesn't works :

import re
import sys

def valid_num(num):
    print num
    p = re.match (r'^[5-6]\d\d', str(num))
    return bool(p) and all(map(lambda n: 540<= int(n)<=600, p.groups()))

a = 699
print valid_num(a)
cs95
  • 274,032
  • 76
  • 480
  • 537
Diwakar SHARMA
  • 470
  • 6
  • 17

2 Answers2

2

If you really want to use regex, I would suggest you something like:

^600|[5][4-9]\d

It will find 600, or 5 followed by a number from 4 to 9, plus another digit

bennes
  • 132
  • 1
  • 7
2

You can write a regex that matches only numbers between 540 and 600 with the following part:

5[4-9]\d|600

So the regex consists out of two possibilities: 5[4-9]\d and 600. The 5[4-9]\d matches any number between 540 and 599 since it starts with a 5 followed by a digit between 4 and 9 and a digit between 0 and 9. 600 matches the 600 number.

Furthermore you probably want to use word boundaries \b to make sure you do not match 56900. So:

\b(?:5[4-9]\d|600)\b

Or in case the string should only contain the number, you should use start and end anchors:

^(?:5[4-9]\d|600)$

So that would result in:

import re

rgx540600 = re.compile(r'^(?:5[4-9]\d|600)$')

def valid_num(num):
    return bool(rgx540600.match(str(num)))

That being said, it is usually not a good idea to do such verifications with a regex. Regex are usually more for syntactical validation whereas for semantical validation, other tools are usually of better use.

Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
  • man where were you all these years , become my teacher and teach me python every day of my life ... than i will ask you a question every day and that will keep both of ur's dementia away – Diwakar SHARMA Jun 10 '17 at 12:14