Perl Regex正则表达式拆分//

我浏览了s'flow和其他站点,以使用Perl中的正则表达式进行简单的解决。

$str = q(//////);#

说我有6个斜杠或7个斜杠,或者其他字符,例如q(aaaaa)

我希望他们像['//','//']一样

我尝试了@my_split = split ( /\/\/,$str);,但没有成功

使用正则表达式可以吗?

这个问题的原因是,说我有这个域名:

$site_name = q(http://www.yahoo.com/blah1/blah2.txt);

我想使用单斜杠拆分以获取“域名”,但我做不到。 我尝试过

split( '/'{1,1},$sitename);#无效。我希望它在一个斜杠上比两个斜杠分开。

谢谢。

jiayoushixin 回答:Perl Regex正则表达式拆分//

这个问题还不清楚。

将字符串分成成对的连续字符

my @pairs = $string =~ /(..)/g;

或通过重复斜杠

拆分字符串
my @parts = split /\/\//,$string;

/.../中的分隔符模式是一个实际的正则表达式,因此我们需要在其内部转义/

但是然后您说您想解析URI?

请使用一个模块。例如,有URI

use warnings;
use strict;
use feature 'say';

use URI;

my $string = q(http://www.yahoo.com/blah1/blah2.txt);
my $uri = URI->new($string);

say "Scheme: ",$uri->scheme;
say "Path:   ",$uri->path;
say "Host:   ",$uri->host;
# there's more,see docs    

然后是URI::Split

use URI::Split qw(uri_split uri_join);

my ($scheme,$auth,$path,$query,$frag) = uri_split($uri);

您可能已经在使用的许多其他模块或框架可以很好地处理URI。

,

这是将完整的URL分成其各个组成部分的快速方法:

my $u = q(http://www.yahoo.com/blah1/blah2.txt);
my ($protocol,$server,$path) = split(/:\/\/([^\/]+)/,$u);
print "($protocol,$path)\n";

h / t @Mike

,

因此,您似乎只想获取域名:

my $url = q(http://www.yahoo.com/blah1/blah2.txt);
my @vars = split /\//,$url;
print $vars[2];

结果:

www.yahoo.com
,

下一段代码就能解决问题

use strict;
use warnings;

use Data::Dumper;

my %url;

while( <DATA> ) {
    chomp;
    m|(\wttps{0,1})://([\w\d\.]+)/(.+)/([^/]+)$|;
    @url{qw(proto dn path file)} = ($1,$2,$3,$4);
    print Dumper(\%url);
}

__DATA__
http://www.yahoo.com/blah1/blah2.txt
http://www.google.com/dir1/dir2/dir3/file.ext
ftp://www.server.com/dir1/dir2/file.ext
https://www.inter.net/dir/file.ext
本文链接:https://www.f2er.com/3078804.html

大家都在问