正则表达式来查找连续的IP地址

2024-06-26 10:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

今天做了一段时间后,我终于不得不认输了。我试图从如下输出中检索所有IP地址:

My Address: 10.10.10.1
  Explicit Route: 192.168.238.90 192.168.252.209 192.168.252.241 192.168.192.209
                  192.168.192.223
  Record   Route:

我需要从“显式路由”和“记录路由”之间提取所有IP地址。我正在使用textfsm,我似乎无法得到我需要的一切。你知道吗


Tags: 路由addressmy记录recordroutetextfsmexplicit
1条回答
网友
1楼 · 发布于 2024-06-26 10:22:44
import re

with open('file.txt', 'r') as file:
    f = file.read().splitlines()
    for line in f:
        found = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', line)
        for f in found:
            print(f)

编辑:

我们打开txt并逐行读取,然后使用正则表达式为每行查找IP(可以有1-3个数字,然后)。重复4次)

网友
2楼 · 发布于 2024-06-26 10:22:44

使用正则表达式和字符串操作:

import re
s = '''My Address: 10.10.10.1
  Explicit Route: 192.168.238.90 192.168.252.209 192.168.252.241 192.168.192.209
                  192.168.192.223
  Record   Route:'''
ips = re.findall(r'\d+\.\d+\.\d+\.\d+', s[s.find('Explicit Route'):s.find('Record   Route')])

相关问题 更多 >