代码之家  ›  专栏  ›  技术社区  ›  rekha_sri

如何验证Perl中的网站URL?

  •  3
  • rekha_sri  · 技术社区  · 15 年前

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

    4 回复  |  直到 11 年前
        1
  •  11
  •   user181548    15 年前
        2
  •  10
  •   brian d foy    15 年前

    我不使用正则表达式。我尝试创建一个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,我可能无论如何都要创建一个对象,所以我最好从它开始。

        3
  •  3
  •   singingfish    15 年前
     use Regexp::Common qw /URI/;
        while (<>) {
            /($RE{URI}{HTTP})/       and  print "$1 is an HTTP URI.\n";
        }
    
        4
  •  2
  •   Paolo Rovelli    11 年前

    既然你说的是“网站URL”,我想你只对HTTP和HTTPS URL感兴趣。

    为此,您可以使用Perl而不是Regex 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)
    

    如果出于任何原因,您实际上想要一个regex,那么您可以使用如下内容来验证http/https/ftp/sftp URL:

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