开发者

How can I match subdirectory paths using a regex in Perl?

开发者 https://www.devze.com 2023-01-15 15:20 出处:网络
I would like to match paths like /this/is/my/dir/name/anything but not /this/is/my/dir/name/anything/anything2. In other words, I want to match all files and sub directories on the first level under `

I would like to match paths like /this/is/my/dir/name/anything but not /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.


You could use the dirname function from File::Basename:

dirname($path) eq '/this/is/my/dir/name' or warn "No match";

UPD: If you prefer to use a regex:

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//. 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). 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消