I'm writing an optimization where you are performing a search for my application and if the string looks like an ip address, then don't bother searching MAC addresses. And if the search looks like a MAC address, don't bother looking in the IP address db column.
I have seen expressions that match ips and mac addresses exactly, but its hard to come by one that matches partial strings and quite a fun brain teaser and I thought I'd get other people's opinions. Right now I have a solution without regex.
use List::Util qw(first);
sub query_is_a_possible_mac_address {
my ($class, $possible_mac) = @_;
return 1 unless $possible_mac;
my @octets = split /:/, $possible_mac, -1;
return 0 if scalar @octets > 6; # fail long MACS
return 0 if (first { $_ !~ m/[^[:xdigit:]]$/ } @octets; # fail any non-hex characters
return not first { hex $_ > 2 ** 8 }; # fail if the number is too big
}
# valid tests
'12:34:56:78:90:12'
'88:11:'
'88:88:F0:0A:2B:BF'
'88'
':81'
':'
'12:34'
'12:34:'
'a'
''
# invalid tests
'88:88:F0:0A:2B:BF:00'
'88z'
'8888F00A2BBF00'
':81a'
'881'
' 88:1B'
'Z'
'z'
'a12:34'
' '
'::88:'