在Perl中是否有正则表达式来查找文件的扩展名?

时间:2010-03-18 01:10:39

标签: perl

Perl中是否有正则表达式来查找文件的扩展名?例如,如果我有“test.exe”,我将如何获得“.exe”?

5 个答案:

答案 0 :(得分:38)

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";

答案 1 :(得分:12)

使用File :: Basename

  use File::Basename;
  ($name,$path,$suffix) = fileparse("test.exe.bat",qr"\..[^.]*$");
  print $suffix;

答案 2 :(得分:4)

\.[^\.]*$

这将为您提供最后一个点之后的所有内容(包括点本身),直到字符串结束。

答案 3 :(得分:4)

这是匹配模式n级扩展文件的正则表达式(例如 .tar.gz .tar.bz2 )。

((\.[^.\s]+)+)$

示例:

#!/usr/bin/perl

my $file1 = "filename.tar.gz.bak";
my ($ext1) = $file1 =~ /((\.[^.\s]+)+)$/;

my $file2 = "filename.exe";
my ($ext2) = $file2 =~ /((\.[^.\s]+)+)$/;

my $file3 = "filename. exe";
my ($ext3) = $file3 =~ /((\.[^.\s]+)+)$/;

my $file4 = "filename.............doc";
my ($ext4) = $file4 =~ /((\.[^.\s]+)+)$/;

print "1) $ext1\n"; # prints "1) .tar.gz.bak"
print "2) $ext2\n"; # prints "2) .exe"
print "3) $ext3\n"; # prints "3) "
print "4) $ext4\n"; # prints "4) .doc"

答案 4 :(得分:3)

您可以使用File::Basename提取任意文件扩展名:

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