如何将其他匹配项排除到此正则表达式?

How can I exclude other matches to this regex?

下面的正则表达式 (ip_regex) 将查找所有 IP 地址,但有一长串我不想匹配的 IP 地址。例如,我需要过滤私有 IP 地址以及其他 public 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

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

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

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