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.