David B
David B

Reputation: 30018

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

Upvotes: 2

Views: 6768

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 150188

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";

Upvotes: 8

Chas. Owens
Chas. Owens

Reputation: 64949

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.

Upvotes: 3

Related Questions