You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python正则匹配两个文本文件中的IP地址与子网

Matching IP Addresses to Subnets from Two Files

Hey there! Let's work through this problem together. You want to find IP addresses from one file that fall within any of the subnets in a second file, and you're looking to use regex as part of the solution. First, let's clear up a key point: regex alone can't check if an IP is inside a subnet—it can only help you validly extract IPs and subnets from your files. We'll need to combine regex with some IP-to-numeric conversion logic to make this work.

First, Let's Fix Your Initial Approach

Your sample code has a few issues we should address:

  • The regex pattern only matches IP-like strings, not subnets (which end with /xx).
  • Once you loop through the subnet file (f2) once, the file pointer stays at the end—so subsequent iterations won't read any content.
  • Most importantly, regex doesn't handle the subnet range calculation.

Step-by-Step Solution

Here's a complete, working script that does what you need:

import re

def ip_to_int(ip):
    """Convert an IP string like '1.1.1.1' to a 32-bit integer."""
    octets = list(map(int, ip.split('.')))
    return (octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3]

def is_ip_in_subnet(ip, subnet):
    """Check if an IP is within a given subnet (format: 'x.x.x.x/xx')."""
    subnet_match = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,2})$', subnet)
    if not subnet_match:
        return False  # Invalid subnet format
    
    subnet_ip = subnet_match.group(1)
    prefix_length = int(subnet_match.group(2))
    
    # Calculate network and broadcast addresses
    ip_int = ip_to_int(ip)
    subnet_int = ip_to_int(subnet_ip)
    mask = (0xFFFFFFFF << (32 - prefix_length)) & 0xFFFFFFFF
    
    network = subnet_int & mask
    broadcast = network | (~mask & 0xFFFFFFFF)
    
    return network <= ip_int <= broadcast

def check(ip_file, subnet_file):
    # Regex pattern to extract valid IP addresses (ignores extra text on lines)
    ip_pattern = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
    
    # Read all subnets first and store them (avoids re-reading the file multiple times)
    subnets = []
    with open(subnet_file, 'r') as f_subnet:
        for line in f_subnet:
            subnet = line.strip()
            if subnet:
                subnets.append(subnet)
    
    # Check each IP against all subnets
    with open(ip_file, 'r') as f_ip:
        for line in f_ip:
            ip_match = ip_pattern.search(line)
            if ip_match:
                ip = ip_match.group(0)
                # Validate the IP is a valid 0-255 octet range (regex can't do this fully)
                try:
                    ip_to_int(ip)  # Will throw error if octets are out of range
                except ValueError:
                    continue
                
                for subnet in subnets:
                    if is_ip_in_subnet(ip, subnet):
                        print(f"IP {ip} matches subnet {subnet}")

# Example usage
check('ip_list.txt', 'subnet_list.txt')

Let's Break This Down

  • ip_to_int: Converts an IP address into a 32-bit integer, which makes it easy to do range comparisons.
  • is_ip_in_subnet: Uses regex to parse the subnet into its base IP and prefix length, then calculates the network and broadcast addresses. It checks if the IP's integer value falls between these two.
  • check:
    • Uses regex to extract IP addresses from lines (even if there's extra text on the line).
    • Reads all subnets first and stores them in a list (more efficient than re-reading the file for every IP).
    • Validates that the extracted IP is actually a valid IP (since regex can't check if octets are between 0-255, we use ip_to_int to catch invalid values).
    • Checks each IP against every subnet and prints matches.

Key Notes

  • The regex \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b ensures we match full IP addresses (not partial ones in longer strings).
  • We use with statements for file handling—this automatically closes files, so you don't have to worry about resource leaks.
  • The subnet validation ensures we only process properly formatted subnets (like 1.1.1.0/28).

内容的提问来源于stack exchange,提问作者Stanislav Aleksiev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:10:58