我正在尝试编写一段代码,使用正则表达式来检查ipv4地址是否正确,但我似乎找不出问题所在。
import re
pattern=re.compile('([0-9]|[1-9][0-9]|1[0-9]{2}|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])')
ip=['17.255.16.45','255.255.255.255','0.0.0.0','0.14.255.14','2555.2564.0.3','0.3.255']
for i in range (len(ip)):
if re.search(pattern,ip[i]):
print(ip[i],'ok')
else:
print(ip[i],"nope")发布于 2019-11-29 03:17:11
我甚至不知道哪里出了问题,但只要我把它重构到这里,它似乎就起作用了:
import re
ip_num_pat = r"[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]"
pattern = re.compile(r'(?:({0})\.){{3}}({0})'.format(ip_num_pat))
ip_addrs = [
'17.255.16.45', '255.255.255.255', '0.0.0.0', '0.14.255.14',
'2555.2564.0.3', '0.3.255']
for ip in ip_addrs:
if pattern.match(ip):
print(ip, 'ok')
else:
print(ip, 'nope')通常,通过将它们拆分成较小的部分,可以更容易地跟踪这些事情。我想最后一块可能是错的。
另外,请注意,我已经将您的代码从.search改为使用.match,。这一点至关重要,因为否则您将匹配像01.2.3.4这样的东西。
但是,正如其他人所说,一种更简单的方法看起来像这样:
ip_addrs = [
'17.255.16.45', '255.255.255.255', '0.0.0.0', '0.14.255.14',
'2555.2564.0.3', '0.3.255', '03.1.2.3']
def is_ip(addr):
try:
component_strings = addr.split(".")
if any(i.startswith("0") and i != "0" for i in component_strings):
raise ValueError("Components cannot start with 0")
components = [int(i) for i in component_strings]
if len(components) != 4:
raise ValueError("Need 4 parts for an IPv4 address")
if any(not 0 <= i < 256 for i in components):
raise ValueError("Components should be in range 0, ..., 255")
return True
except ValueError:
return False
for ip in ip_addrs:
if is_ip(ip):
print(ip, 'ok')
else:
print(ip, 'nope')https://stackoverflow.com/questions/59094836
复制相似问题