Reputation: 67
I'm trying to use regex and I have a limit for input numbers, I want them to be less or equal to 255:
def validate(ip):
try:
x = re.search(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$", ip.strip())
for pot in x.groups():
if int(pot) <= 255:
return True
else:
return False
except:
return False
validate('64.128.256.512')
well the problem is when I use a for loop, and using return, it checks only for one group of number (I mean the first one 64) and ignores the other, so the result will be True, but what I expect is False.
Upvotes: 1
Views: 166
Reputation: 16496
Because return
exits the function. You should first iterate through all the values and check to see if there is an invalid case. This can be done using all()
like:
import re
def validate(ip):
x = re.search(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$", ip.strip())
if not x:
return False
if all(int(pot) <= 255 for pot in x.groups()):
return True
return False
print(validate("64.128.256.512"))
print(validate("64.128.250.212"))
print(validate("foo.128.boo.212"))
output:
False
True
False
Note1: I guess it's an exercise, because there are more robust ways to validate IP addresses. I just fixed the problem you had.
Note2: Since you check for \d
in your pattern, you don't need to add that try-except. If another non-digit value is provided, search
will give you None
and with the check if not x:
you can simply return.
Upvotes: 2
Reputation: 67
the most simple way i founded was:
def validate(ip):
try:
x = re.search(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$", ip.strip())
n = 0
for pot in x.groups():
if int(pot) > 255:
n += 1
if n != 0:
return False
return True
except:
return False
Upvotes: 0
Reputation: 13242
Regex is overkill here (for a non-robust method of validation) imo~
def validate(ip):
split_ip = ip.split('.')
return len(split_ip) == 4 and all(x <= 255 for x in map(int, split_ip))
>>> validate('64.128.256.512')
False
>>> validate('64.128.255.123')
True
>>> validate('64.128.255')
False
Upvotes: 2
Reputation: 187
It seems like you're trying to validate an IP address using regex.
This article covers that.
It suggests using this regex to validate an IPv4 address.
"(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
Upvotes: 0