通过 python 正则表达式忽略 ip 地址的第一个八位字节中的这两个数字(以 127 或 0 开头)

Ignore these two numbers (starts with 127 or 0) in the first octet of the ip address through python regex

我有一个存储在文本文件中的 IP 列表以及一些其他数据,我试图从中仅 grep 有效的 IP。在这里,我有一些 IP,例如 0.0.0.0 和本地主机 IP(以 127 开头...),我试图使用正则表达式消除这些 IP。 这是我想出的用于过滤 0.0.0.0 IP 但无法有效删除 127..* IP 的正则表达式模式。

import re
with open("data","r") as f:
    for line in f:
        test = re.search(r'(?!0|127)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line)
        if test:
            print(test.group(0))

IP 在文本文件中如下所示:

127.3.65.7
alkjgfbvui vluiybr vk ru r127.0.0.1fal;iufnaw  waoun
12.0.1.5
mjhgvjg0.0.0.0kjuycuj
0.0.0.0
0.0.0.0
gare bloing r pgnao wyin212.2.174.64
207.71.31.224
awuie nvp; vwa rv;awiu n ;lkirjght94.206.93.104ta;wourit mrt'
172.20.128.1
172.20.164.207
172.20.164.203
172.20.164.209
1.8.0.144

我得到以下输出,您可以看到以 127 开头的 IP 也通过删除第一个数字“1”打印出来

27.3.65.7
27.0.0.1
12.0.1.5
212.2.174.64
207.71.31.224
94.206.93.104
172.20.128.1
172.20.164.207
172.20.164.203
172.20.164.209
1.8.0.144

试试正则表达式:(?<!\d)(?!0|127)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}

Demo

解释:

在 \d 后面添加一个负向查找以消除以 27 开头的匹配项