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

What is the simplest way to use a regex to take the filename from a path? for example to extract file.dll from
c:\windows\system32\file.dll

Replies are listed 'Best First'.
Re: simple regex question
by runrig (Abbot) on Dec 02, 2009 at 18:24 UTC
Re: simple regex question
by kennethk (Abbot) on Dec 02, 2009 at 18:27 UTC
    Rather than using a regular expression, it's probably better to use the existing code base to do your job for you. In this case, the core module File::Spec can parse the path for you using the splitpath method.

    However, if there's a good reason to do it with a regular expression, you can use:

    /([^\\]*)$/

    which will match and extract all the characters between the last backslash and the end of the string. Note this will fail on to do what you want on non-MS systems. See perlretut for more regular expression information.

Re: simple regex question
by TomDLux (Vicar) on Dec 02, 2009 at 20:58 UTC

    If you don't want to use File::Basename or File::Spec, you still shouldn't use regexen. Why use a complicated machine which many parameters, when what you want is a salami-slicer?

    If you don't use the clean and simple tools, use split. Of course you have to decipher whether to split on '/' for Macs or unix, '\' for Windows, was it ':' on VMS?, or something else ... all that is handled for you if you use the right tool. After you split, just take the last component and that's the filename.

    --
    TTTATCGGTCGTTATATAGATGTTTGCA