Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

This is probably pretty simple for Regular Expression experts like you guys. So thanks a lot in advance. I am trying to extract the fully-qualified path of the parent folder of a file. For example, if I have a fully-qualified path for a file "C:\Temp\Stuff\test.txt", I want to have a regular expression that will return me the string "C:\Temp\Stuff". Ideally this will need to work on files with or without extensions. Any help is greatly appreciated. Thanks a lot!
  • Comment on RegEx to get filepath for parent folder

Replies are listed 'Best First'.
Re: RegEx to get filepath for parent folder
by davido (Cardinal) on Mar 06, 2004 at 06:34 UTC
    This is really more of a job for the File::Basename module than a job for a goofy regexp. With the module you could just do this:

    use File::Basename; my $dirname = dirname ("lib/this/that/other.txt");

    However, if you're sure that the path delimeter is a slash (either forward or backslash), and that the slash characters won't comprise part of a name, you could probably get away with a regexp like this:

    ($path, $filename) = $fullpath =~ m/^(.*[/\\])([^/\\]+)/;

    Since it's easy to goof the Regexp (and mine is untested), you're better off using the module mentioned above. It's a lot better to rely on good tested code than a homebrewed complicated regexp, most of the time.

    Update: I wanted to note that File::Spec and File::Basename are both part of the core Perl distribution, and thus, probably came standard with your implementation of Perl.


    Dave

      Thank you so very much. Did not know about the existence of File::Basename. Worked like a charm!
Re: RegEx to get filepath for parent folder
by leira (Monk) on Mar 06, 2004 at 06:31 UTC
    I think the File::Spec module will give you what you need.

    Linda