Is there a regular expression in Perl to find a fi

2020-08-09 06:04发布

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

标签: perl
5条回答
在下西门庆
2楼-- · 2020-08-09 06:39
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";
查看更多
Viruses.
3楼-- · 2020-08-09 06:48

Here it is a regex to match pattern n-level extension file (e.g. .tar.gz or .tar.bz2).

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

Example:

#!/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楼-- · 2020-08-09 06:51

use File::Basename

  use File::Basename;
  ($name,$path,$suffix) = fileparse("test.exe.bat",qr"\..[^.]*$");
  print $suffix;
查看更多
手持菜刀,她持情操
5楼-- · 2020-08-09 06:51

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";
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-08-09 07:03
\.[^\.]*$

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

查看更多
登录 后发表回答