gpt4 book ai didi

完整和部分 IP 的 python IP 验证 REGex 验证

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:32 30 4
gpt4 key购买 nike

我正在尝试验证输入以查看它是否是有效的 IP 地址(可能是部分地址)。

可接受的输入:172、172.112、172.112.113、172.112.113.114

Not Acceptable 输入:1724,172.11113 等等

这是我创建的一个函数来检查它(但是它验证了 Not Acceptable 输入,如 1724,我似乎无法修复它......请帮忙)

def ipcheck(ip):
ippattern_str = '(([1-2]?[\d]{1,2}\.?){0,1}(\.[1-2]?[\d]{1,2}){0,1}(\.[1-2]?[\d]{1,2}\.){0,1}(([1-2]?[\d]{1,2}[\D\W]*)'
ippattern = re.compile(ippattern_str)
# ippattern is now used to call match, passing only the ip string
global matchip
matchip = ippattern.match(ip)
return matchip


ip = sys.argv[1]
ipcheck(ip)

print matchip

我觉得也许我需要正确使用 anchor ?我尽我所知尝试了一切,我们将不胜感激。

最佳答案

也许你可以避免使用正则表达式并让 python socket.inet_aton做这个工作:

import socket

try:
socket.inet_aton(addr)
# correct IP
except socket.error:
# bad IP

对于 inet_aton,有效的 IP 地址是以下形式:

       a.b.c.d
a.b.c
a.b
a

In all of the above forms, components of the dotted address can be specified in decimal, octal (with a leading 0), or hexadecimal, with a leading 0X). Addresses in any of these forms are collectively termed IPV4 numbers-and-dots notation. The form that uses exactly four decimal numbers is referred to as IPv4 dotted-decimal notation (or sometimes: IPv4 dotted-quad notation).

source

关于完整和部分 IP 的 python IP 验证 REGex 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8269376/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com