基本上,你想要的是:
google.com -> google.com -> google
www.google.com -> google.com -> google
google.co.uk -> google.co.uk -> google
www.google.co.uk -> google.co.uk -> google
www.google.org -> google.org -> google
www.google.org.uk -> google.org.uk -> google
可选:
www.google.com -> google.com -> www.google
images.google.com -> google.com -> images.google
mail.yahoo.co.uk -> yahoo.co.uk -> mail.yahoo
mail.yahoo.com -> yahoo.com -> mail.yahoo
www.mail.yahoo.com -> yahoo.com -> mail.yahoo
您不需要构建一个不断变化的正则表达式,因为如果您只需查看名称的倒数第二部分,99% 的域都会正确匹配:
(co|com|gov|net|org)
如果是其中之一,则需要匹配 3 个点,否则需要匹配 2 个。简单。现在,我的正则表达式魔法与其他一些 SO'ers 的魔法不匹配,所以我发现实现这一目标的最佳方法是使用一些代码,假设您已经剥离了路径:
my @d=split /\./,$domain; # split the domain part into an array
$c=@d; # count how many parts
$dest=$d[$c-2].'.'.$d[$c-1]; # use the last 2 parts
if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
$dest=$d[$c-3].'.'.$dest; # if so, add a third part
};
print $dest; # show it
根据您的问题,仅获取名称:
my @d=split /\./,$domain; # split the domain part into an array
$c=@d; # count how many parts
if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
$dest=$d[$c-3]; # if so, give the third last
$dest=$d[$c-4].'.'.$dest if ($c>3); # optional bit
} else {
$dest=$d[$c-2]; # else the second last
$dest=$d[$c-3].'.'.$dest if ($c>2); # optional bit
};
print $dest; # show it
我喜欢这种方法,因为它无需维护。除非你想验证它实际上是一个合法的域,但那是没有意义的,因为你很可能只使用它来处理日志文件,而一个无效的域一开始就不会找到它的方式。
如果您想匹配“非官方”子域,例如 bozo.za.net 或 bozo.au.uk,bozo.msf.ru 只需将 (za|au|msf) 添加到正则表达式。
我很想看到有人只使用一个正则表达式来完成所有这些,我相信这是可能的。