检查字符串是否与python中的IP地址模式匹配? [英] check if a string matches an IP address pattern in python?

查看:47
本文介绍了检查字符串是否与python中的IP地址模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查字符串是否与特定模式匹配的最快方法是什么?正则表达式是最好的方法吗?

What is the fastest way to check if a string matches a certain pattern? Is regex the best way?

例如,我有一堆字符串,想检查每个字符串是否是有效的 IP 地址(在这种情况下有效意味着格式正确),使用正则表达式执行此操作的最快方法是什么?或者有什么更快的东西,比如字符串格式之类的.

For example, I have a bunch of strings and want to check each one to see if they are a valid IP address (valid in this case meaning correct format), is the fastest way to do this using regex? Or is there something faster with like string formatting or something.

到目前为止,我一直在做这样的事情:

Something like this is what I have been doing so far:

for st in strs:
    if re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', st) != None:
       print 'IP!'

推荐答案

update:下面的原始答案适用于 2011 年,但自 2012 年以来,使用 Python 的 ipaddress stdlib 模块 - 除了检查 IPv4 和 IPv6 的 IP 有效性之外,它还可以还可以做很多其他事情.</update>

update: The original answer bellow is good for 2011, but since 2012, one is likely better using Python's ipaddress stdlib module - besides checking IP validity for IPv4 and IPv6, it can do a lot of other things as well.</update>

您似乎正在尝试验证 IP 地址.正则表达式可能不是最好的工具.

It looks like you are trying to validate IP addresses. A regular expression is probably not the best tool for this.

如果您想接受所有有效的 IP 地址(包括一些您可能甚至不知道有效的地址),那么您可以使用 IPy (来源):

If you want to accept all valid IP addresses (including some addresses that you probably didn't even know were valid) then you can use IPy (Source):

from IPy import IP
IP('127.0.0.1')

如果 IP 地址无效,则会抛出异常.

If the IP address is invalid it will throw an exception.

或者你可以使用 socket (来源):

import socket
try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

如果您真的只想匹配具有 4 个小数部分的 IPv4,那么您可以在点上拆分并测试每个部分是 0 到 255 之间的整数.

If you really want to only match IPv4 with 4 decimal parts then you can split on dot and test that each part is an integer between 0 and 255.

def validate_ip(s):
    a = s.split('.')
    if len(a) != 4:
        return False
    for x in a:
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255:
            return False
    return True

请注意,您的正则表达式不会执行此额外检查.它将接受 999.999.999.999 作为有效地址.

Note that your regular expression doesn't do this extra check. It would accept 999.999.999.999 as a valid address.

这篇关于检查字符串是否与python中的IP地址模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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