tags:

views:

286

answers:

4

Is there a regular expression in Perl to find a file's extension? For example, if I have "test.exe", how would I get the ".exe"?

+2  A: 
\.[^\.]*$

This would give you everything after the last dot (including the dot itself) until the end of the string.

Dean Harding
+7  A: 
my $file = "test.exe";

# Match a dot, followed by any number of non-dots until the
# end of the line.
my ($ext) = $file =~ /(\.[^.]+)$/;

print "$ext\n";
Gavin Brock
+2  A: 

You could use File::Basename to extract an arbitrary file extension:

use strict;
use warnings;
use File::Basename;
my $ext = (fileparse("/foo/bar/baz.exe", qr/\.[^.]*/))[2];
print "$ext";
toolic
+3  A: 

use File::Basename

  use File::Basename;
  ($name,$path,$suffix) = fileparse("test.exe.bat",qr"\..[^.]*$");
  print $suffix;
ghostdog74
I've never thought that File::Basename was any good for this job considering that you have to supply the pattern that you could have used with the match operator to get the same thing done.
brian d foy
if its just to get extension, a normal regex would suffice. But File::Basename parses the rest of the path as well. If OP needs to get them besides extension need, File::Basename comes in handy.
ghostdog74