[英]How can I match subdirectory paths using a regex in Perl?
I would like to match paths like /this/is/my/dir/name/anything
but not /this/is/my/dir/name/anything/anything2
. 我想匹配
/this/is/my/dir/name/anything
类的路径,但不是/this/is/my/dir/name/anything/anything2
。 In other words, I want to match all files and sub directories on the first level under ``/this/is/my/dir/name/`, but not anything on lower levels. 换句话说,我希望在第一级匹配``/ this / is / my / dir / name /`下的所有文件和子目录,但不要匹配更低级别的任何文件和子目录。
You could use the dirname
function from File::Basename
: 您可以使用
File::Basename
的dirname
函数:
dirname($path) eq '/this/is/my/dir/name' or warn "No match";
UPD: If you prefer to use a regex: UPD:如果您更喜欢使用正则表达式:
my $dirname = '/this/is/my/dir/name';
$path =~ m|^$dirname/[^/]+/?$| or warn "No match";
The slashes present a problem for the default delimiters, you wind up with the leaning toothpick problem . 斜线对于默认分隔符存在问题,最终会出现倾斜的牙签问题 。 Luckily, Perl 5 allows you choose your own delimiter if you use the general form:
m//
. 幸运的是,如果你使用一般形式,Perl 5允许你选择自己的分隔符:
m//
。 Given that you want to match the whole string instead of just a substring, you will want to use anchors that specify start of string ( ^
) and end of string ( $
) : 假设您想要匹配整个字符串而不仅仅是子字符串,您将需要使用指定字符串开头(
^
)和字符串结尾( $
)的锚点:
if ($dirname =~ m{^/this/is/my/dir/name/anything$}) {
}
Note: the ^
and $
anchors are affected by the /m
modifier (they change to mean start and end of line instead). 注意:
^
和$
anchors受/m
修饰符的影响 (它们改为意味着行的起点和终点)。 If you are going to use the /m
modifier, you may want to use the \\A
(start of string) and \\Z
(end of string or before a newline at the end of the string) or \\z
(end of string) assertions . 如果要使用
/m
修饰符,可能需要使用\\A
(字符串的开头)和\\Z
(字符串的结尾或字符串末尾的换行符之前)或\\z
(字符串的结尾)断言 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.