您可以用正則表達式做到這一點,但它少得多的工作,讓URI庫爲你做。在路徑之前和之後(查詢,錨點,授權...),您都不會被有趣的方案,轉義和額外的東西所困擾。繞path_segments()表示路徑的方式存在一些問題。有關詳細信息,請參閱下面的註釋和the URI docs。
我假設http://www.example.com/foo/
被視爲頂級目錄。必要時進行調整,但必須考慮一些事項。
#!/usr/bin/env perl
use URI;
use File::Spec;
use strict;
use warnings;
use Test::More 'no_plan';
sub is_top_level_uri {
my $uri = shift;
# turn it into a URI object if it isn't already
$uri = URI->new($uri) unless eval { $uri->isa("URI") };
# normalize it
$uri = $uri->canonical;
# split the path part into pieces
my @path_segments = $uri->path_segments;
# for an absolute path, which most are, the absoluteness will be
# represented by an empty string. Also /foo/ will come out as two elements.
# Strip that all out, it gets in our way for this purpose.
@path_segments = grep { $_ ne '' } @path_segments;
return @path_segments <= 1;
}
my @filtered_uris = (
"http://www.example.com/hello.html",
"http://www.example.com/",
"http://www.example.com",
"https://www.example.com/",
"https://www.example.com/foo/#extra",
"ftp://www.example.com/foo",
"ftp://www.example.com/foo/",
"https://www.example.com/foo/#extra",
"https://www.example.com/foo/?extra",
"http://www.example.com/hello.html#extra",
"http://www.example.com/hello.html?extra",
"file:///foo",
"file:///foo/",
"file:///foo.txt",
);
my @unfiltered_uris = (
"http://www.foo.com/this/thingrighthere.html",
"https://www.example.com/foo/bar",
"ftp://www.example.com/foo/bar/",
"file:///foo/bar",
"file:///foo/bar.txt",
);
for my $uri (@filtered_uris) {
ok is_top_level_uri($uri), $uri;
}
for my $uri (@unfiltered_uris) {
ok !is_top_level_uri($uri), $uri;
}
'http:// example.com/foo /'下降的方式是?注意尾部斜線。 – Schwern