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

Python 2.7路由表IP地址精准匹配替换问题求助

Fixing Precise IP Replacement in Route Table Processing Script

Hey there! Let's tackle that annoying partial IP match issue you're facing. Your current script uses basic string replacement, which doesn't distinguish between a full IP like 5.6.7.8 and a longer IP that contains it (like 5.6.7.88). Here's how to adjust your code to get precise matches, plus some other optimizations:

Key Issues in the Original Code

  • Partial IP Matches: str.replace() replaces any occurrence of the substring, even if it's part of a longer IP address.
  • Redundant Loops: You're looping through subnet_list multiple times for the same replacement, which is unnecessary.
  • Manual File Handling: Explicitly calling close() can lead to resource leaks if an error occurs; using with statements is safer.

Improved Solution with Regular Expressions

We'll use Python's re module to match full IP addresses using word boundaries, and restructure the code for clarity and efficiency:

import re

# Configuration - use a dictionary to map subnets to customer names (cleaner than separate lists)
infile = "routes.txt"
outfile = "output.txt"
delete_text = ["ROUTER1# sh run | i route", "ip route"]
ip_to_customer = {
    "1.2.3.4": "CUST_A",
    "5.6.7.8": "CUST_B"
}

# Use 'with' statements to auto-close files
with open(infile, 'r') as fin, open(outfile, 'w+') as fout:
    for line in fin:
        # Step 1: Remove redundant text
        for text in delete_text:
            line = line.replace(text, "")
        
        # Step 2: Precise IP replacement using regex word boundaries
        for ip, cust_name in ip_to_customer.items():
            # \b matches word boundaries, re.escape ensures dots in IP are treated as literal dots
            regex_pattern = rf'\b{re.escape(ip)}\b'
            line = re.sub(regex_pattern, cust_name, line)
        
        # Write the processed line to output
        fout.write(line)

# Verify the output
with open(outfile, 'r') as f:
    file_contents = f.read()
    print(file_contents)

What's Changed?

  • Dictionary Mapping: Combining subnets and customer names into a dictionary makes the code easier to maintain (add/remove entries in one place).
  • Regex for Precise Matching:
    • \b ensures we only match the full IP address (not part of a longer one).
    • re.escape(ip) escapes the dots in the IP address, since dots in regex match any character—this ensures we match the literal IP.
  • Safer File Handling: with statements automatically close files when done, even if an error occurs during processing.

Testing This Solution

If your input routes.txt has lines like:

ROUTER1# sh run | i route ip route 1.2.3.4 255.255.255.0 next-hop
ROUTER1# sh run | i route ip route 5.6.7.8 255.255.255.0 next-hop
ROUTER1# sh run | i route ip route 5.6.7.88 255.255.255.0 next-hop

The output will correctly be:

CUST_A 255.255.255.0 next-hop
  CUST_B 255.255.255.0 next-hop
  5.6.7.88 255.255.255.0 next-hop

Notice that 5.6.7.88 remains unchanged, while the exact IPs are replaced as intended.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:24:35