正则表达式获取解析inet值

问题描述 投票:0回答:1

我想解析 ifconfig 来获取 ip_address、网络掩码和广播。这些是可选字段。如果存在,则应返回,但如果不存在,则应返回 None。

我的下面的模式工作正常,但如果“inet6”不存在。如果不是,则此模式返回 None。我不知道为什么它仍然试图与inet6匹配。

output = """
en0: flags=8863<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1a:2b:3c:4d:5e
    inet6 fe80::1a2b:3c4d:5e6f:7g8h prefixlen 64 secured scopeid 0x4
    inet 192.168.1.10 netmask 0xffffff00 broadcast 192.168.1.255
"""

# Regex pattern to capture MAC, IPv4 (inet), and IPv6 (inet6) addresses
pattern = re.compile(r'ether (?P<mac_address>[a-f0-9:]+).*?'
                     r'(?:\s+inet (?P<ip_address>[\d\.]+) '
                     r'netmask (?P<netmask>0x[a-f0-9]+) '                      
                     r'broadcast (?P<broadcast>[.a-f0-9:]+))?.*?')

print(pattern.search(output).groupdict())
python-3.x regex python-re
1个回答
0
投票

尝试:

ether (?P<mac_address>[a-f0-9:]+)(?:(?!inet\b)[\w\W])+(?:inet (?P<ip_address>[\d.]+) netmask (?P<netmask>0x[a-f0-9]+) broadcast (?P<broadcast>[.a-f0-9:]+))?

参见:regex101

参见 Python 演示

import re

output = """
en0: flags=8863<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1a:2b:3c:4d:5e
    inet6 fe80::1a2b:3c4d:5e6f:7g8h prefixlen 64 secured scopeid 0x4
    inet 192.168.1.10 netmask 0xffffff00 broadcast 192.168.1.255
"""

# Regex pattern to capture MAC, IPv4 (inet), and IPv6 (inet6) addresses
pattern = re.compile(r'ether (?P<mac_address>[a-f0-9:]+)(?:(?!inet\b)[\w\W])+(?:inet (?P<ip_address>[\d.]+) netmask (?P<netmask>0x[a-f0-9]+) broadcast (?P<broadcast>[.a-f0-9:]+))?')

print(pattern.search(output).groupdict())

说明

  • ether (?P<mac_address>[a-f0-9:]+)
    :你的以太部分
  • (?:
    :然后使用脾气暴躁的贪婪令牌
    • (?!inet\b)
      :断言您完全匹配
      inet
    • [\w\W]
      :任何字符(包括换行符)
  • )+
  • (?:inet (?P<ip_address>[\d.]+) netmask (?P<netmask>0x[a-f0-9]+) broadcast (?P<broadcast>[.a-f0-9:]+))?
    :然后是你的inet、网络掩码、广播部分
© www.soinside.com 2019 - 2024. All rights reserved.