Regex使用通配符验证域


Regex to validate domains with wildcards

我正在PHP中的DNS面板上工作,我必须验证一个没有尾随点的DNS记录名称。以下是几个例子:

example.com - match
sub.example.com - match
sub.sub.example.com - match
*.example.com - match
*.sub.example.com - match
sub.*.example.com - no mach
sub*.example.com - no match
*sub.example.com - no match

我目前正在使用这个正则表达式,但问题是它与通配符(*)不匹配:

^(?!'-)(?:[a-z'd'-]{0,62}[a-z'd]'.){1,126}(?!'d+)[a-z'd]{1,63}$

我不太擅长格式化正则表达式。实现这一目标的最佳方式是什么?谢谢

我发现了一个使用regex的解决方案,它不完全尊重域规则,但它足够好,所以如果你打算使用它,我建议你做额外的检查:

^('*'.)?([a-z'd][a-z'd-]*[a-z'd]'.)+[a-z]+$

有一种更好的方法可以通过PHP解决这个问题:

$tmp = $domain_to_check;
if(strpos($tmp, '*.') === 0){
    $tmp = substr($tmp, 2);
}
if(filter_var('http://' . $tmp, FILTER_VALIDATE_URL)){
    // The format is valid
}else{
    // The format is invalid
}