2016-01-20 135 views
1

有没有更好的方法来使用正则表达式捕获分组编写下面的代码?Perl正则表达式捕获分组

我期待在录制后立即获取文件夹名称。

#!/usr/bin/perl 
use strict; 
use warnings; 
use Data::Dumper; 

my $path1 = '\\server1\Recordings\AU-AR-Online\Outbound\20160120\52031\52031-14-07-16.wav'; 
my $path2 = '\\server2\e$\Recordings\SU-AC-Online\Outbound\20160120\52031\52031-14-07-16.wav'; 

my @paths = ($path1,$path2); 

foreach my $path (@paths) { 
    # Split path into fields 
    my @array = (split /\\/, $path); 

    # Get index of Recordings 
    my($index)= grep { $array[$_] eq "Recordings" } 0..$#array; 

    # Brand always follows Recordings 
    print $array[$index+1]; 

} 

回答

2

当然,只需更换你的循环与此内容:

my ($brand) = $path =~ m|\\Recordings\\([^\\]+)| or die "Not found"; 
print $brand; 
1

捕获的文件夹后直接Recordings\

my ($brand) = $path =~ m{ Recordings \\ ([^\\] +) }x) 

使用的正则表达式的x修饰符意味着空格是忽略,这可以帮助使正则表达式更具可读性。

如果品牌文件夹始终是倒数第五次,你可能分裂的路径和负索引抓住它。

my $brand = (split /\\/, $path)[-5]; 

但是,只有当品牌总是倒数第五时才有效。我不知道你的数据集是什么。

另外,如果你有路径的工作,有许多模块(如Path::Tiny),使人们更容易获得父/子/绝对路径,基本名称等