使用Python验证 IP 地址而不使用 RegEx
给定一个 IP 地址作为输入,任务是编写一个Python程序来检查给定的 IP 地址是否有效,而不使用 RegEx。
什么是 IP(互联网协议)地址?
每台连接到 Internet 的计算机都由一个唯一的四部分字符串标识,称为其 Internet 协议 (IP) 地址。 IP 地址(版本 4)由以句点分隔的四个数字(每个数字在 0 到 255 之间)组成。 IP 地址的格式是 32 位数字地址,以句点分隔的四个十进制数字(称为八位字节)书写;每个数字都可以写为 0 到 255(例如 – 0.0.0.0 到 255.255.255.255)。
例子:
Input: 192.168.0.1
Output: Valid Ip address
Input: 110.234.52.124
Output: Valid Ip address
Input: 666.1.2.2
Output: Invalid Ip address
方法 #1:使用count()方法检查周期数,然后检查每个周期之间的数字范围。
Python3
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# check number of periods
if s.count('.') != 3:
return 'Invalid Ip address'
l = list(map(str, s.split('.')))
# check range of each number between periods
for ele in l:
if int(ele) < 0 or int(ele) > 255:
return 'Invalid Ip address'
return 'Valid Ip address'
# Driver Code
print(isValidIP('666.1.2.2'))
Python3
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# initialize counter
counter = 0
# check if period is present
for i in range(0, len(s)):
if(s[i] == '.'):
counter = counter+1
if(counter != 3):
return 0
# check the range of numbers between periods
st = set()
for i in range(0, 256):
st.add(str(i))
counter = 0
temp = ""
for i in range(0, len(s)):
if(s[i] != '.'):
temp = temp+s[i]
else:
if(temp in st):
counter = counter+1
temp = ""
if(temp in st):
counter = counter+1
# verifying all conditions
if(counter == 4):
return 'Valid Ip address'
else:
return 'Invalid Ip address'
# Driver Code
print(isValidIP('110.234.52.124'))
输出
Invalid Ip address
方法#2:使用变量检查周期数,使用集合检查周期之间的数字范围是否在 0 到 255(含)之间。
蟒蛇3
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# initialize counter
counter = 0
# check if period is present
for i in range(0, len(s)):
if(s[i] == '.'):
counter = counter+1
if(counter != 3):
return 0
# check the range of numbers between periods
st = set()
for i in range(0, 256):
st.add(str(i))
counter = 0
temp = ""
for i in range(0, len(s)):
if(s[i] != '.'):
temp = temp+s[i]
else:
if(temp in st):
counter = counter+1
temp = ""
if(temp in st):
counter = counter+1
# verifying all conditions
if(counter == 4):
return 'Valid Ip address'
else:
return 'Invalid Ip address'
# Driver Code
print(isValidIP('110.234.52.124'))
输出:
Valid Ip address