sách gpt4 ai đã đi

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

In lại 作者:太空宇宙 更新时间:2023-11-04 07:11:32 39 4
mua khóa gpt4 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 ?我尽我所知尝试了一切,我们将不胜感激。

1 Câu trả lời

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

import socket

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

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

       a.b.c.d
a.b.c
a.b
Một

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).

nguồn

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

39 4 0
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com