在Python中捕获特定IP地址集的正则表达式

2024-10-04 05:32:09 发布

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

我的输出如下

0.0.0.0/0
  unicast-ip4-chain
  [@0]: dpo-load-balance: [proto:ip4 index:86 buckets:1 uRPF:102 to:[0:0]]
    [0] [@0]: dpo-drop ip4
0.0.0.0/32
  unicast-ip4-chain
  [@0]: dpo-load-balance: [proto:ip4 index:87 buckets:1 uRPF:88 to:[0:0]]
    [0] [@0]: dpo-drop ip4
1.1.1.254/32
  unicast-ip4-chain
  [@0]: dpo-load-balance: [proto:ip4 index:72 buckets:1 uRPF:41 to:[0:0]]
    [0] [@5]: ipv4 via 2.2.2.254 VirtualFuncEthernet0/7/0.1540: mtu:1500 f8c001181ac0fa163e81a6c0810006040800
14.1.1.0/32
  unicast-ip4-chain
  [@0]: dpo-load-balance: [proto:ip4 index:14 buckets:1 uRPF:111 to:[0:0]]
    [0] [@0]: dpo-drop ip4
14.1.1.1/32
  unicast-ip4-chain
  [@0]: dpo-load-balance: [proto:ip4 index:54 buckets:1 uRPF:61 to:[1228:75011]]
    [0] [@5]: ipv4 via 14.1.1.1 VirtualFuncEthernet0/7/0.1540: mtu:1500 f8c001181ac0fa163e81a6c0810006040800

为了从输出中获取值2.2.2.254,我编写了regexp,如下所示

var = 1.1.1.254/32
re.findall(var+r'.*ipv4\s+via\s+(\W+)', x1)

电流输出为[]


Tags: tochainindexloadviadropprotoipv4
2条回答

你可以用

(?ms)^1\.1\.1\.254/32\n.*?ipv4\s+via\s+(\d[\d.]*)

regex demo

详细信息

  • (?ms)-re.Mre.DOTALL已启用
  • ^-行的开始
  • 1\.1\.1\.254/32-1.1.1.254/32字符串
  • \n-换行符
  • .*?-任何0个或更多字符尽可能少
  • ipv4\s+via\s+-ipv4,1+空格,via,1+空格
  • (\d[\d.]*)-捕获组1:一个数字,然后是0个或更多数字/点

Python demo

import re
text = "0.0.0.0/0\n  unicast-ip4-chain\n  [@0]: dpo-load-balance: [proto:ip4 index:86 buckets:1 uRPF:102 to:[0:0]]\n    [0] [@0]: dpo-drop ip4\n0.0.0.0/32\n  unicast-ip4-chain\n  [@0]: dpo-load-balance: [proto:ip4 index:87 buckets:1 uRPF:88 to:[0:0]]\n    [0] [@0]: dpo-drop ip4\n1.1.1.254/32\n  unicast-ip4-chain\n  [@0]: dpo-load-balance: [proto:ip4 index:72 buckets:1 uRPF:41 to:[0:0]]\n    [0] [@5]: ipv4 via 2.2.2.254 VirtualFuncEthernet0/7/0.1540: mtu:1500 f8c001181ac0fa163e81a6c0810006040800\n14.1.1.0/32\n  unicast-ip4-chain\n  [@0]: dpo-load-balance: [proto:ip4 index:14 buckets:1 uRPF:111 to:[0:0]]\n    [0] [@0]: dpo-drop ip4\n14.1.1.1/32\n  unicast-ip4-chain\n  [@0]: dpo-load-balance: [proto:ip4 index:54 buckets:1 uRPF:61 to:[1228:75011]]\n    [0] [@5]: ipv4 via 14.1.1.1 VirtualFuncEthernet0/7/0.1540: mtu:1500 f8c001181ac0fa163e81a6c0810006040800"
v = "1.1.1.254/32"
m = re.search(rf"^{re.escape(v)}\n.*?ipv4\s+via\s+(\d[\d.]*)", text, re.M|re.DOTALL)
if m:
    print(m.group(1))
# => 2.2.2.254

如果要在下一个IP之前保存整个文本块,请尝试以下操作: https://regex101.com/r/wCHYvj/2

(1\.1\.1\.254\/32)(\s*|.*)+?(?=\d{1,3}.\d{1,3}.\d{1,3})

查找给定IP并捕获,直到新行中的下一个IP

相关问题 更多 >