我有一个类似于
的网址//google.com/Ucomm/Photos/1984 Digital Photos/blah blah/Reflections Magazine/Fall 1984 issue/This is what I want 7-28/TMI_7840_xx.PNG
每个网址都不同但我想要的是相同的部分,它就是文件名之前的部分 我想如果我计算了反斜杠的数量,我可以打印出第二个到最后一个和最后一个之间的内容。
所以输出看起来像
This is what I want 7-28
到目前为止我所知道的反斜杠的数量,但我不知道如何打印我需要的东西。
守则:
my $string = $cells[74];
my $count = lc($string) =~ tr/\///;
print $count;
答案 0 :(得分:6)
你不需要计算斜杠(那些是正斜杠,而不是反斜杠),只需从最后开始并向后工作。
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
my $string = "//google.com/Ucomm/Photos/1984 Digital Photos/blah blah/Reflections Magazine/Fall 1984 issue/This is what I want 7-28/TMI_7840_xx.PNG";
say "Version 1";
{
my @parts = split '/', $string;
say $parts[-2];
}
say "Version 2"; # if you love regular expressions
{
my ($captured) = $string =~ m!/([^/]+)/[^/]+$!;
say $captured;
}
答案 1 :(得分:2)
您可以使用basename
和dirname
:
use File::Basename;
my $str="//google.com/Ucomm/Photos/1984 Digital Photos/blah blah/Reflections Magazine/Fall 1984 issue/This is what I want 7-28/TMI_7840_xx.PNG";
print basename(dirname($str));
或者,split
/
上的字符串,并采用前一个元素。
答案 2 :(得分:2)
您可以使用split
my @data = split('/', $string);
print $data[-2];
答案 3 :(得分:0)
将输入分解为数组。问题是:如何识别你想要的领域?按位置?
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;
# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;
my $string = '//google.com/Ucomm/Photos/1984 Digital Photos/blah blah/Reflections Magazine/Fall 1984 issue/This is what I want 7-28/TMI_7840_xx.PNG';
my @array = split /\//, $string;
print Dumper \@array;
__END__
答案 4 :(得分:0)
您可以使用正则表达式:
if ($str=~/([^\/]*)\/([^\/]*)$/) {
print "$1\n"
} else {
print "ERROR\n"
}
示例:
perl -e '$str="google.com/Ucomm/Photos/1984 Digital Photos/blah blah/Reflections Magazine/Fall 1984 issue/This is what I want 7-28/TMI_7840_xx.PNG"; if ($str=~/([^\/]*)\/([^\/]*)$/) {print "$1\n"} else {print "ERROR\n"}'
This is what I want 7-28