RegEx - 匹配除00:00:00:00:00:00之外的所有MAC地址

时间:2011-03-10 23:46:28

标签: c# regex

我有一个包含多个MAC地址的字符串。如何匹配除00:00:00:00:00:00之外的所有MAC?

我用来匹配MAC的正则表达式:

((?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2})

2 个答案:

答案 0 :(得分:3)

坦率地说,我建议分两部分来做。首先使用正则表达式获取所有单个地址,然后只需从列表中删除任何归零地址。这是......

  1. 最有可能计算成本较低,而且
  2. 比正则表达式的大量片段更容易阅读和维护。

答案 1 :(得分:1)

这是你需要做的模式:

(?!(?:00[:-]){5}00)((?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2})

编辑 - @ trev的答案“你怎么能这样做?”

use strict; use warnings;

my @samps = (
 'MATCH_ME mac1=11:22:33:44:55:66 mac2=00:11:22:33:44:55',
 'MATCH_ME mac1=00:00:00:00:00:00 mac2=00:11:22:33:44:55',
 'MATCH_ME mac1=11:22:33:44:55:66 mac2=00:00:00:00:00:00',
 'MATCH_ME mac1=00:00:00:00:00:00 mac2=00:00:00:00:00:00',
);

for (@samps) {

   if ( /(MATCH_ME)\s*
           mac1=
              (   (?!(?:00[:-]){5}00)
                  (?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}
                |
              )
              .*?
           mac2=
              (   (?!(?:00[:-]){5}00)
                  (?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}
                |
              )
        /x )
   {
     print "'$1'\n";
     print "'$2'\n";
     print "'$3'\n",'-'x20,"\n";
   }
}

输出

'MATCH_ME'
'11:22:33:44:55:66'
'00:11:22:33:44:55'
--------------------
'MATCH_ME'
''
'00:11:22:33:44:55'
--------------------
'MATCH_ME'
'11:22:33:44:55:66'
''
--------------------
'MATCH_ME'
''
''