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

Can someone toss me a regex that would take something like image.gif, sound.wav, video.mpeg, etc. and return just the file extensions?

Replies are listed 'Best First'.
Re: regex to return file extensions
by davido (Cardinal) on Apr 02, 2004 at 06:42 UTC
    I'm assuming that you've got the filename isolated already. If not, the File::Basename module is great. Then to get the extension, use something like this:

    print "$1\n" if $filename =~ m/\.([^.]+)$/;


    Dave

      When you are already using File::Basename to extract the filename, then the following is also an option
      ($name, $path, $suffix) = fileparse('/home/foo/bar.txt', qr{[^.]*}); # or if you have a list of allowed suffices in @suf @suf = qw/gif wav mpeg txt/; ($name, $path, $suffix) = fileparse('/home/foo/bar.txt', @suf); # both lead to # $name eq 'bar.' # $path eq '/home/foo' # $suffix eq 'txt'

      -- Hofmator

Re: regex to return file extensions
by matija (Priest) on Apr 02, 2004 at 06:08 UTC
    something like
    $file=~/\.(\w+)$/;
    would probably do the trick.
      \z except when the extension ends in a newline :)
Re: regex to return file extensions
by Anonymous Monk on Apr 02, 2004 at 09:18 UTC
    use strict; while(<*.*>) { $extension =~ /\.([^\.]+)$/g; push(@extarray, $1); } print join("\n", @extarray);

    janitored by ybiC: Balanced <code> tags around codeblock

Re: regex to return file extensions
by eial (Initiate) on Apr 03, 2004 at 09:37 UTC
    im use this and work very fine: my ($filename,$extension) =~ m/(.*)\.(.*)/; if the filename is fjgdkfjkgs........................gif, well it regex return fjgdkfjkgs....................... to the filename and gif to extensions. Success