从字符串中提取特定数据

2024-05-18 22:13:35 发布

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

我在下面有一个字符串,我需要从中获得各个接口的具体配置,我需要能够解析的示例

interface Loopback0
  ip address 1.1.1.1/32
  no shutdown
  isis enable 2222
  isis passive

或者能够

interface Management0
  no sflow enable
  ip address 1.1.1.2/31
  no shutdown
  isis enable 2222
  isis passive

接口下的行数可能不同

字符串为:

[hostname router\r\n!\r\ninterface Loopback0\r\n  ip address 1.1.1.1/32\r\n  no shutdown\r\n isis enable 2222\r\n  isis passive\r\n!\r\nvrf definition MGMT\r\n  rd 200:200\r\n!\r\n!\r\nvrf definition VRF_DDOS\r\n  rd 2222:100\r\n  description VRF_DDOS\r\n!\r\n!\r\n interface ethernet1/1\r\n  no sflow enable\r\n ip address 1.1.1.2/31\r\n  no shutdown\r\n isis enable 2222\r\n  isis passive\r\n!\r\nvrf definition MGMT\r\n  rd 200:200\r\n!\r\n!\r\nvrf definition VRF_DDOS\r\n  rd 2222:100\r\n  description VRF_DDOS\r\n!\r\n!\r\n ]

Tags: no字符串ipaddressenablerdinterfaceisis
1条回答
网友
1楼 · 发布于 2024-05-18 22:13:35

Checkouthttps://pythex.org/and学习如何使用RegEx

如果在exmaple文本中输入字符串并使用(\d.\d.\d.\d/\d\d)作为模式,它将收集每个IP地址

import re

ip_address = re.findall(r'(\d.\d.\d.\d/\d\d)', string)

print(ip_address)
>>> 1.1.1.1/32, 1.1.1.2/31

或者,如果输出总是相同的,则可以在“\”处拆分字符串并获取每个项的索引

示例:

feedback = "[hostname router\r\n!\r\ninterface Loopback0\r\n ip address 1.1.1.1/32\r\n no shutdown\r\n isis " \
              "enable 2222\r\n isis passive\r\n!\r\nvrf definition MGMT\r\n rd 200:200\r\n!\r\n!\r\nvrf definition" \
              " VRF_DDOS\r\n rd 2222:100\r\n description VRF_DDOS\r\n!\r\n!\r\n interface ethernet1/1\r\n no sflow " \
              "enable\r\n ip address 1.1.1.2/31\r\n no shutdown\r\n isis enable 2222\r\n isis passive\r\n!\r\nvrf " \
              "definition MGMT\r\n rd 200:200\r\n!\r\n!\r\nvrf definition VRF_DDOS\r\n rd 2222:100\r\n description " \
              "VRF_DDOS\r\n!\r\n!\r\n ]".replace('\r\n','').split(' ')

print(feedback[2:6])

output >>> ['Loopback0', 'ip', 'address', '1.1.1.1/32']

相关问题 更多 >

    热门问题