Trev
Trev

Reputation: 1377

RegEx - Match all MAC addresses except for 00:00:00:00:00:00

I have a string with multiple MAC addresses. How do I match all MACs except 00:00:00:00:00:00?

The regex I use to match a MAC:

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

Upvotes: 0

Views: 1602

Answers (2)

user557597
user557597

Reputation:

This is the pattern you would need to do that:

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

Edit - an answer to @trev's "how could you do this?"

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";
   }
}

output

'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'
''
''

Upvotes: 1

Karl Nicoll
Karl Nicoll

Reputation: 16429

Frankly I'd recommend doing it in two parts. First fetch all the individual addresses using your regex, and then simply remove any zeroed addresses from the list. This is...

  1. Most likely less computationally expensive, and
  2. Far easier to read and maintain than a massive kludge of a regular expression.

Upvotes: 3

Related Questions