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.
views:
88answers:
2
+6
A:
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";
eugene y
2010-09-12 11:45:07
+1 Thanks, this works, but I would like a regex for this (I'm using this with a bunch of other tests).
David B
2010-09-12 11:54:32
@David: regexes are not the best option here -- File::Basename was written to take care of the messy edge cases in filename parsing. There should be no reason why you can't use it in conjunction with other tests.
Ether
2010-09-12 16:44:18
+2
A:
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.
Chas. Owens
2010-09-12 13:42:42
+1 thank you, that's useful! I understand that the expression after the `m` can be enclosed by `{}` or `||` or `//`?
David B
2010-09-12 13:46:59
@David B: Yes. Can't recall the official description, but [this one explains that too](http://perldoc.perl.org/perlop.html#Gory-details-of-parsing-quoted-constructs).
Dummy00001
2010-09-12 13:59:58
@David B In Perl 5, you may choose any delimiter but whitespace characters. There are four bracketing delimiter sets: `[]`, `{}`, `()`, and `<>`. In all other cases you one character like this `m#regex#` or `s#regex#string#`. The delimiter `'` is also special. It turns the construct into a non-interpolating version of itself.
Chas. Owens
2010-09-12 14:22:46