简体   繁体   English

用于匹配IPV4地址的Python正则表达式不起作用

[英]Python regular expression to match IPV4 address doesn't work

I'm using the re library. 我正在使用re库。

def validate_ip(self, ip):
    pattern = re.compile(r'([01]?[0-9]?[0-9]|2[0-4][0-9]|2[5][0-5])\.{4}')
    matchObj = re.match(pattern, ip)

    if matchObj == None:
        print "Invalid IP:", ip
        sys.exit(0)

When I pass the IP 192.0.0.0 , the output is: 当我通过IP 192.0.0.0时 ,输出是:

Invalid IP: 192.0.0.0

Why is it not matching? 为什么不匹配?

Your pattern matches one 3-digit number, followed by exactly 4 dots: 您的模式匹配一​​个3位数字,后跟恰好4个点:

>>> pattern = re.compile(r'([01]?[0-9]?[0-9]|2[0-4][0-9]|2[5][0-5])\.{4}')
>>> pattern.match('255....')
<_sre.SRE_Match object at 0x1026eda80>

The {4} doesn't apply to everything preceding it; {4}不适用于它之前的所有内容; it only applies to just the \\. 它仅适用于只是 \\. .

You want this instead: 你想要这个:

r'(([01]?[0-9]?[0-9]|2[0-4][0-9]|2[5][0-5])\.){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|2[5][0-5])'

This matches your number pattern plus a . 这符合您的数字模式加上a . dot 3 times, because now the {3} applies to everything in the preceding grouped expression (using (...) ). 3次,因为现在{3}适用于前面的分组表达式中的所有内容(使用(...) )。 You then still need to match the last digit group separately. 然后,您仍需要分别匹配最后一个数字组。

Demo: 演示:

>>> pattern = re.compile(r'(([01]?[0-9]?[0-9]|2[0-4][0-9]|2[5][0-5])\.){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|2[5][0-5])')
>>> pattern.match('192.0.0.0')
<_sre.SRE_Match object at 0x1023bf588>

As an aside, just use if not match: to test for a match failure; 顺便说一下, if not match:使用if not match:测试匹配失败; None is a false value in a boolean context. None在布尔上下文中是false值。 Even if you really wanted to test for None , you should be using if match is None: , using an identity test. 即使你真的想测试None ,你也应该使用if match is None: ,使用身份测试。

If you can use Python 3.3+, use the ipaddress library. 如果您可以使用Python 3.3+,请使用ipaddress库。

import ipaddress

for ip in ["192.0.0.0", "0.0.0.0", "192.168.0.256"]:
    try:
        ipaddress.ip_address(ip)
        print("{} is valid".format(ip));
    except ValueError:
        print("{} is invalid".format(ip))

Output: 输出:

192.0.0.0 is valid
0.0.0.0 is valid
192.168.0.256 is invalid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM