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

Good day Bros. I want to write a regexp that would match only the filename portion of a quoted windoze path\filename string like "C:\Communications%20by%20Date\1995\19950711%20UBL%20An%20Open%20Letter%20to%20King.pdf" In other words I only want to match the part from the last backslash up to the quote. I can't figure it out. Everything I try like \\.+?\.pdf matches everything from the first backslash on. Can anyone tell me how to do it?

TIA...Steve

Replies are listed 'Best First'.
Re: Regexp match filename, exclude path
by Corion (Patriarch) on Oct 04, 2008 at 17:08 UTC

    Your try, \\.+?\.pdf matches:

    1. A backslash
    2. As little anything as is possible, nongreedy
    3. a dot and then pdf

    I think what you would want, instead of matching As little anything as is possible, nongreedy you want Anything except a backslash.

    More likely, you just want basename from File::Basename.

      Right. I realize why the regexp I tried doesn't work. The solution can't be anything except a backslash, it has to be something like the last set of characters that isn't preceded by a backslash. I realize I could do this with a module, splitting on backslashes then taking the last element, etc., but I want to do it with a regexp if I can.

        I'm not sure what you mean by

        The solution can't be anything except a backslash, it has to be something like the last set of characters that isn't preceded by a backslash.

        The following will match the last sequence of non-backslash characters in your string, which is what you seem to want:

        m![^\\]+\.pdf$!;

        Anchoring the match makes sure you get the filename path, and the character set negation makes sure you get nothing with a backslash in it.

Re: Regexp match filename, exclude path
by Narveson (Chaplain) on Oct 04, 2008 at 18:01 UTC
    qr{ [^\\/]+ # one or more non-slash characters $ # the end of the string }x
    Update: added the x.
Re: Regexp match filename, exclude path
by bichonfrise74 (Vicar) on Oct 04, 2008 at 18:29 UTC
    Can you try something like this?
    $a = "C:\Communication..."; ($b) = $a =~ m/.*\\(.*)/;
Re: Regexp match filename, exclude path
by poolpi (Hermit) on Oct 05, 2008 at 10:32 UTC

    To perform operations on filenames,
    see this core module File::Spec

    #!/usr/bin/perl -w use strict; use File::Spec; my $path = q{C:\Communications%20by%20Date\1995\19950711%20UBL%20An%20 +Open%20Letter%20to%20King.pdf}; my ($volume,$directories,$file) = File::Spec->splitpath( $path ); print $file, "\n"; __END__ Output : 19950711%20UBL%20An%20Open%20Letter%20to%20King.pdf

    hth,
    PooLpi

    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb