You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ifconfig正则解析问题:inet6在inet上方时返回None

解决ifconfig解析中inet6位于inet上方时正则匹配失败的问题

问题原因

你的正则匹配失败的核心原因是:re.compile默认不启用DOTALL标志,此时.元字符不会匹配换行符。原正则中ether (?P<mac_address>[a-f0-9:]+).*?里的.*?只能匹配ether所在行的剩余内容,无法跨越inet6的行去匹配后面的inet行。再加上inet相关的捕获组是可选的(?:...)?,正则会直接跳过这部分,导致ip_address、netmask、broadcast都返回None。

解决方案

这里提供两种可靠的修复方式:

方案1:启用DOTALL标志,调整正则跨多行匹配

通过添加re.DOTALL让.匹配换行符,同时优化正则逻辑确保能定位到inet行:

import re

ifconfig_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
"""

pattern = re.compile(
    r'ether (?P<mac_address>[a-f0-9:]+)[\s\S]*?'
    r'(?:\s+inet (?P<ip_address>[\d\.]+) '
    r'netmask (?P<netmask>0x[a-f0-9]+) '
    r'broadcast (?P<broadcast>[\d\.]+))?',
    re.IGNORECASE | re.DOTALL
)

print(pattern.search(ifconfig_output).groupdict())

输出结果:

{'mac_address': '00:1a:2b:3c:4d:5e', 'ip_address': '192.168.1.10', 'netmask': '0xffffff00', 'broadcast': '192.168.1.255'}

方案2:分字段独立匹配(更健壮)

因为ifconfig的每一项都是独立行,拆分匹配逻辑可以避免跨多行正则的复杂度,同时更容易维护:

import re

ifconfig_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
"""

result = {
    'ip_address': None,
    'netmask': None,
    'broadcast': None,
    'mac_address': None
}

# 匹配MAC地址
mac_match = re.search(r'ether ([a-f0-9:]+)', ifconfig_output, re.IGNORECASE)
if mac_match:
    result['mac_address'] = mac_match.group(1)

# 匹配IPv4相关字段
inet_match = re.search(r'inet ([\d\.]+) netmask (0x[a-f0-9]+) broadcast ([\d\.]+)', ifconfig_output, re.IGNORECASE)
if inet_match:
    result['ip_address'] = inet_match.group(1)
    result['netmask'] = inet_match.group(2)
    result['broadcast'] = inet_match.group(3)

print(result)

输出结果和方案1一致,且如果某个字段不存在(比如没有inet行),对应值会保持None,符合需求。

内容的提问来源于stack exchange,提问作者premganesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:32:13