转换MAC地址格式 [英] Convert MAC Address Format

查看:480
本文介绍了转换MAC地址格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了一个小小的脚本,用来从交换机中提取数百个MAC地址进行比较,但它们的格式为0025.9073.3014,而不是标准的00:25:90:73:30:14 / p>

我对如何转换这个问题感到st where不安,最好的办法就是把它们分解成。,然后再分解成2个部分每一个,然后用:分隔符重新加入所有的部分。

我用hacky的方法可以,但是这是困扰我,因为这是一个非常糟糕的方法。有没有什么办法可以更好地完成这项工作? >和 preg_replace

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

首先剥离,然后添加 .. 两个任意字符(?!$)如果不是最后。



eval.in测试

a>





或者使用

  $ str = preg_replace('html'rel =nofollow> capture group ) 〜(..)(?!$)\。?〜','\ 1:',$ str); 

在regex101.com上测试



性能没有太大的区别。


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.

Test at eval.in


Or use a capture group and do it without str_replace:

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

Test at regex101.com

There's not much difference in performance.

这篇关于转换MAC地址格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆