我想根据给定的目录路径拆分一个目录,并与perl中的默认目录进行比较,最好是regex中的默认目录。我有两个默认目录,假设是/root/demo/和/etc/demo/。
给定一个目录路径,假设是/root/demo/home/test/sample/somefile.txt或/etc/demo/home/test/sample/somefile.txt,
我想从给定的目录路径中解压/home/test/sample/somefile.txt。敬请协助。
谢谢
发布于 2014-11-02 22:28:42
Use \K丢弃以前匹配的字符。
\/(?:root|etc)\/demo\K\S+DEMO
发布于 2014-11-03 02:27:07
将您的前缀目录列表构建到正则表达式alteration中。请确保按length降序排序,并使用quotemeta。
下面演示了:
use strict;
use warnings;
my @dirs = qw(
/root/demo
/etc/demo
);
# Sorted by length descending in case there are subdirs.
my $list_dirs = join '|', map {quotemeta} sort { length($b) <=> length($a) } @dirs;
while (<DATA>) {
chomp;
if ( my ($subdir) = m{^(?:$list_dirs)(/.*)} ) {
print "$subdir\n";
}
}
__DATA__
/root/demo/home/test/sample/someroot.txt
/etc/demo/home/test/sample/someetc.txt输出:
/home/test/sample/someroot.txt
/home/test/sample/someetc.txt发布于 2014-11-03 02:46:23
这是另一种使用quotemeta的方法。
Perl示例:
use strict;
use warnings;
my @defaults = ('/root/demo/', '/etc/demo/');
$/ = undef;
my $testdata = <DATA>;
my $regex = '(?:' . join( '|', map(quotemeta($_), @defaults) ) . ')(\S*)';
print $regex, "\n\n";
while ( $testdata =~ /$regex/g )
{
print "Found /$1\n";
}
__DATA__
/root/demo/home/test/sample/somefile.txt
/etc/demo/home/test/sample/somefile.txt 输出:
(?:\/root\/demo\/|\/etc\/demo\/)(\S*)
Found /home/test/sample/somefile.txt
Found /home/test/sample/somefile.txthttps://stackoverflow.com/questions/26700378
复制相似问题