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
"?
views:
286answers:
4
+2
A:
\.[^\.]*$
This would give you everything after the last dot (including the dot itself) until the end of the string.
Dean Harding
2010-03-18 01:12:32
+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
2010-03-18 01:14:24
+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
2010-03-18 02:02:32
+3
A:
use File::Basename
use File::Basename;
($name,$path,$suffix) = fileparse("test.exe.bat",qr"\..[^.]*$");
print $suffix;
ghostdog74
2010-03-18 02:06:22
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
2010-03-18 03:58:03
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
2010-03-18 04:39:17