使用正则表达式查找有效的IP地址 [英] Finding valid IP addresses with regex

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

问题描述

我有以下字符串:

text = '10.0.0.1.1 but 127.0.0.256 1.1.1.1'

我想返回有效的IP地址,因此它只应返回 1.1 .1.1 此处 256 高于 255 且第一个IP数字太多。

and I want to return the valid IP addresses, so it should only return 1.1.1.1 here since 256 is higher than 255 and the first IP has too many numbers.

到目前为止,我有以下内容,但它不适用于 0-255 要求。

so far I have the following but it doesn't work on the 0-255 requirement.

text = "10.0.0.1.1 but 127.0.0.256 1.1.1.1"
l = []
import re
for word in text.split(" "):
    if word.count(".") == 3:
        l = re.findall(r"[\d{1,3}]+\.[\d{1,3}]+\.[\d{1,3}]+\.[\d{1,3}]+",word)


推荐答案

这是一个非常好的python正则表达式从字符串中获取有效IPv4 IP地址的工作:

Here is a python regex that does a pretty good job of fetching valid IPv4 IP addresses from a string:

import re
reValidIPv4 = re.compile(r"""
    # Match a valid IPv4 in the wild.
    (?:                                         # Group two start-of-IP assertions.
      ^                                         # Either the start of a line,
    | (?<=\s)                                   # or preceeded by whitespace.
    )                                           # Group two start-of-IP assertions.
    (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)    # First number in range 0-255 
    (?:                                         # Exactly 3 additional numbers.
      \.                                        # Numbers separated by dot.
      (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)  # Number in range 0-255 .
    ){3}                                        # Exactly 3 additional numbers.
    (?=$|\s)                                    # End IP on whitespace or EOL.
    """, re.VERBOSE | re.MULTILINE)

text = "10.0.0.1.1 but 127.0.0.256 1.1.1.1"
l = reValidIPv4.findall(text)
print(l)

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

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