【问题标题】:How can I exclude other matches to this regex?如何排除此正则表达式的其他匹配项?
【发布时间】:2020-11-22 07:51:57
【问题描述】:

下面的正则表达式 (ip_regex) 将找到所有 IP 地址,但有一长串我不想匹配的 IP 地址。例如,我需要过滤私有 IP 地址以及其他公共 IP。我怎样才能添加到这个正则表达式来完成这个?

    import re
    fh = "some file.txt"
    fh2 = "some file2.txt"
    ip_regex = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
    
    for line in fh:
        line = line.strip()
        match = ip_regex.findall(line)
        if match:
            for (ip) in match:
                print('\n'.join(match), file=fh2)
        else:
            pass

【问题讨论】:

标签: list python-3.7


【解决方案1】:

我建议您使用ìp 变量来构建IPAddress[1] 对象。然后你可以在它上面调用isPrivate() 方法,或者询问它是否包含在IPv4Network 中。这会有点冗长,但是排除随机子网的通用正则表达式会以可读性较差的代码结尾。

在修改后的 sn-p 中,我还更改了一条对我来说似乎是错误的行(那里有注释)。

import re
from ipaddress import IPv4Address
fh = 'ips.txt'
fh2= open ('filtereds.txt', 'w')
ip_regex = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")

with open (fh, "r") as myfile:
    data=myfile.readlines()
    for line in data:
        line = line.strip()
        match = ip_regex.findall(line)
        if match:
            for (ip) in match:
                ipaddress = IPv4Address(ip)
                if ipaddress.is_global: # and other criterias
                    # print('\n'.join(match), file=fh2) this would print all the line (with other IPs that does not fit criteria)
                    print(ip, file=fh2) #this would print only the matched IP
        else:
            pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多