#===================== example #my $reg=net2preg("147.210.0.0/17"); # #my $teststring= " 195.22.199.1 - 147.210.0.0 - 147.210.127.255 - 147.210.128.0 - 9147.210.0.0 147.210.127.00 \n"; # #$teststring=~ s/($reg)/($1)/g; # #print $teststring; #======================= result : # 195.22.199.1 - (147.210.0.0) - (147.210.127.255) - 147.210.128.0 - 9147.210.0.0 147.210.127.00 #======================= sub net2preg { # Usage : net2preg(subnet) -- ipv4 subnet in x.x.x.x/n form # build a perl regexp that exaclty match all ip from the given subnet. # warning: the subnet *must* have it's hosts bits part to zero. # ex: 147.210.1.0/16 is not good => 147.210.0.0/16 is ok # (to correct this, the /n mask should be applied on the subnet part) ## 02/2005 - Laurent FACQ - facq@u-bordeaux.fr - LGPL ## Want to include this function in a lib/package ? Great ! Please, contact me, i have other ones :) my ($net)= @_; my ($subnet,$bits)= split("/",$net); my ($ip1,$ip2,$ip3,$ip4)= split('\.',$subnet); my $delta; my $octet= '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'; $reg1= $ip1; $reg2= $ip2; $reg3= $ip3; $reg4= $ip4; if ($bits!=32) { if ($bits>24) { $delta= 2**(32-$bits)-1; $reg4= '(?:'.join('|',($ip4..$ip4+$delta)).')'; } else { $reg4= $octet; if ($bits>16) { $delta= 2**(24-$bits)-1; $reg3= '(?:'.join('|',($ip3..$ip3+$delta)).')'; } else { $reg3= $octet; if ($bits>8) { $delta= 2**(16-$bits)-1; $reg2= '(?:'.join('|',($ip2..$ip2+$delta)).')'; } else { $reg2= $octet; if ($bits>0) { $delta= 2**(8-$bits)-1; $reg1= '(?:'.join('|',($ip2..$ip2+$delta)).')'; } else { $reg1= $octet; } } } } } # debug html ! #$reg =~ s//>/g; print $reg; ### no digit before nor after (look-behind, loog-ahead) return "(?:(?