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

正则解析ifconfig输出异常:无inet6时匹配返回None求助

问题分析与解决方案

你的正则匹配问题根源在于未启用re.DOTALL标志,默认情况下正则中的.无法匹配换行符,导致当没有inet6条目时,正则无法跨多行匹配到后续的inet内容,进而出现预期外的匹配结果。

修改后的正则与代码

import re

# 测试无inet6的场景
output = """
en0: flags=8863<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1a:2b:3c:4d:5e
    inet 192.168.1.10 netmask 0xffffff00 broadcast 192.168.1.255
"""

# 优化后的正则:开启DOTALL支持跨多行匹配,修正broadcast的字符类
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>[\d\.]+))?',
                     re.DOTALL | re.IGNORECASE)

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

关键调整说明

  1. re.DOTALL标志:让.可以匹配换行符,确保正则能跨多行捕获ether之后的inet条目,无论中间是否有inet6内容。
  2. 修正broadcast字符类:将[.a-f0-9:]+改为[\d\.]+,因为广播地址是IPv4格式,不需要包含冒号。
  3. re.IGNORECASE标志:兼容大小写形式的MAC地址(比如00:1A:2B这类格式)。

测试结果

  • 当存在inet条目时,输出包含对应字段值:
    {'mac_address': '00:1a:2b:3c:4d:5e', 'ip_address': '192.168.1.10', 'netmask': '0xffffff00', 'broadcast': '192.168.1.255'}
    
  • 当没有inet条目时,对应字段返回None:
    {'mac_address': '00:1a:2b:3c:4d:5e', 'ip_address': None, 'netmask': None, 'broadcast': 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 08:16:09