regex - Perl regular expression for partially matching an ip or mac address -


i'm writing optimization performing search application , if string looks ip address, don't bother searching mac addresses. , if search looks mac address, don't bother looking in ip address db column.

i have seen expressions match ips , mac addresses exactly, hard come 1 matches partial strings , quite fun brain teaser , thought i'd other people's opinions. right have solution without regex.

use list::util qw(first);  sub query_is_a_possible_mac_address {   ($class, $possible_mac) = @_;   return 1 unless $possible_mac;    @octets = split /:/, $possible_mac, -1;   return 0 if scalar @octets > 6; # fail long macs   return 0 if (first { $_ !~ m/[^[:xdigit:]]$/ } @octets; # fail non-hex characters   return not first { hex  $_ > 2 ** 8 }; # fail if number 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:' 

given (new) tests, works:

/^[0-9a-fa-f]{0,2}(:[0-9a-fa-f]{2}){0,5}:?$/ 

here lines match given above tests (note single hex characters 'a' , 'a' correctly matched:

12:34:56:78:90:12 88:11: 88:88:f0:0a:2b:bf 88 :81 : 12:34 12:34: '' (<-- empty space) 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -