使用正则表达式查找有效的IP地址

时间:2014-01-10 15:25:30

标签: python regex ip

我有以下字符串:

text = '10.0.0.1.1 but 127.0.0.256 1.1.1.1'

我希望返回有效的IP地址,因此它应该只返回1.1.1.1,因为256高于255且第一个IP的数字太多。

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

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)

1 个答案:

答案 0 :(得分:2)

这是一个python正则表达式,可以很好地从字符串中获取有效的IPv4 IP地址:

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)