python IP验证完整和部分IP的REGex验证 [英] python IP validation REGex validation for full and partial IPs

查看:75
本文介绍了python IP验证完整和部分IP的REGex验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to validate the input to see if it a valid IP address(could be a partial one).

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

Acceptable input : 172, 172.112, 172.112.113, 172.112.113.114

不可接受的输入:1724,172.11113等等

Unacceptable input: 1724,172.11113 etc etc

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

Heres a function that I created to check it (however it validates unacceptable input like 1724 which I cant seem to fix..please help)

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

我觉得我可能需要正确使用锚点?我已经尽力了解所有知识,任何帮助都会受到赞赏。

I feel like maybe I need to use anchors properly? Ive tried everything to my best knowledge, any help would be appreciated.

推荐答案

这个正则表达式可以解决这个问题:

This regex would do the trick:

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){0,3}$

确保给定的数字在正确的范围内(0-255)并且可以有1-4个部分。

It ensures that the given numbers are in the correct range (0-255) and can have 1-4 parts.

您可以在此处看到它: http:// regexr。 com?2va3j

You can see it in action here: http://regexr.com?2va3j

这篇关于python IP验证完整和部分IP的REGex验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆