簡體   English   中英

正則表達式捕獲 Python 中的特定 IP 地址集

[英]Regular Expression to Capture specific set of IP Address in Python

我的 output 如下

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

為了從 output 中捕獲值 2.2.2.254,我編寫了如下的正則表達式。

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

當前 output 為 []

您可以使用

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

查看正則表達式演示

細節

  • (?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 演示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM