python mac地址转换,转换MAC地址格式

I just wrote a small script to pull hundreds of MAC Addresses from a switch for comparison, however they are formatted as "0025.9073.3014" rather than the standard "00:25:90:73:30:14".

I am stumped on how to convert this, where the best I can come up with is exploding these into pieces at the ".", then breaking them down further into 2 pieces each, then rejoin all parts with ":" separators.

I am okay with hacky methods but this is bothering me because that is a very poor approach. Is there any way to perform this better?

解决方案

A combination of str_replace and preg_replace:

$str = preg_replace('~..(?!$)~', '\0:', str_replace(".", "", $str));

First stripping out the . then adding : after .. two of any characters (?!$) if not at the end.

Or use a capture group and do it without str_replace:

$str = preg_replace('~(..)(?!$)\.?~', '\1:', $str);

There's not much difference in performance.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值