简体   繁体   English

通过python regex忽略IP地址的第一个八位字节中的这两个数字(以127或0开头)

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

I have a list of IP's stored in a text file along with some other data from which I am trying to grep only the valid IP's. 我有一个存储在文本文件中的IP列表以及一些其他数据,这些数据我试图仅从其中提取有效IP。 Here, I have some IP's like 0.0.0.0 and localhost IP's (starts with 127...) which I am trying to eliminate using regex. 在这里,我有一些IP,例如0.0.0.0和localhost IP(以127 ...开头),我正尝试使用正则表达式消除它们。 Here is the regex pattern I came up with that filters 0.0.0.0 IP's but couldn't effectively remove the 127..* IP's. 这是我想到的过滤器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))

The IP's are in the text file like this: 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

I am getting the following output where you can see IP's that starts with 127 is also printed by just removing the first digit '1' 我得到以下输出,在其中您可以看到仅删除第一个数字“ 1”也可以打印以127开头的IP

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

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

Demo 演示

Explanation: 说明:

Add a negative look behind for \\d to eliminate matches starting with 27 在\\ d后面加上否定的外观以消除以27开头的匹配项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM