繁体   English   中英

如何验证Perl中的网站URL?

[英]How can I validate a website URL in Perl?

我需要一个正则表达式来使用Perl验证网站URL。

我不使用正则表达式。 我尝试创建一个URI对象,看看会发生什么。 如果它工作,我有一个URI对象,我可以查询以获得该方案(其他东西变成“无方案”URI)。

use URI;

while( <DATA> )
    {
    chomp;
    my $uri = URI->new( $_, 'http' );
    if( $uri->scheme ) { print "$uri is a URL\n"; }
    else               { print "$uri is not a URL\n"; }
    }

__END__
foo.html
http://www.example.com/index.html
abc
www.example.com

如果我正在寻找特定类型的URI,我可以查询该对象以查看它是否满足我需要的任何内容,例如特定的域名。 如果我正在使用URL,我可能会创建一个对象,所以我不妨从它开始。

 use Regexp::Common qw /URI/;
    while (<>) {
        /($RE{URI}{HTTP})/       and  print "$1 is an HTTP URI.\n";
    }

由于您所说的是“网站网址”,我想您只对HTTP和HTTPS网址感兴趣。

为此,您可以使用Perl的Data :: Validate :: URI模块,而不是使用正则表达式。

例如,要验证HTTP和HTTPS URL:

use Data::Validate::URI;
my $url = "http://google.com";
my $uriValidator = new Data::Validate::URI();

print "Valid web URL!" if $uriValidator->is_web_uri($url)

并且,仅验证HTTP URL:

print "Valid HTTP URL!" if $uriValidator->is_http_uri($url)

最后,验证任何格式良好的URI:

print "Valid URI!" if $uriValidator->is_uri($url)

相反,出于任何原因,您实际上想要一个正则表达式,那么您可以使用类似以下内容来验证HTTP / HTTPS / FTP / SFTP URL:

print "Valid URL!\n" if $url =~ /^(?:(?:https?|s?ftp))/i;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM