使用正则表达式在python中验证IP地址 [英] ip address validation in python using regex

查看:65
本文介绍了使用正则表达式在python中验证IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的 ip 地址验证中,我想看看它是否是一个有效的 ip 地址,我如何使用下面的 re 来做到这一点

<预><代码>>>>ip="241.1.1.112343434">>>aa=re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^0-9]",ip)>>>aa.group()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'NoneType' 对象没有属性 'group'

解决方案

改用锚点:

aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)

这些确保字符串的开始和结束在正则表达式的开始和结束处匹配.(好吧,从技术上讲,您不需要起始 ^ 锚点,因为它隐含在 .match() 方法中).

然后,在尝试访问其结果之前检查正则表达式是否确实匹配:

if aa:ip = aa.group()

当然,这不是验证 IP 地址的好方法(请查看 gnibbler 的答案以获取正确方法).但是,正则表达式可用于检测较大字符串中的 IP 地址:

ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)

在这里,\b 词边界锚确保每个段的数字不超过 3.

In the following ip address validation i want to see if it a valid ip address or not how can i do this using the below re

>>> ip="241.1.1.112343434" 
>>> aa=re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^0-9]",ip)
>>> aa.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

解决方案

Use anchors instead:

aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)

These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^ anchor because it's implicit in the .match() method).

Then, check if the regex did in fact match before trying to access its results:

if aa:
    ip = aa.group()

Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:

ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)

Here, the \b word boundary anchors make sure that the digits don't exceed 3 for each segment.

这篇关于使用正则表达式在python中验证IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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