2

Quick Perl Snippet: Finding If A File Has A Media Extension Using Regex


Posted by Artem Russakovskii on March 21st, 2008 in Programming

Updated: May 1st, 2008

Sometimes in my line of work, I need to figure out if a url or filename point to a media file by checking for the file extension. If it's a url, however, it may be followed by various parameters. Not to overcomplicate things, I came up with the following Perl code:

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/perl -w
use strict;
my $name = "some_file.flv"; # or http://example.com/file.mp4?foo=bar
my $is_media_type = ($name =~ /\.(wmv|avi|flv|mov|mkv|mp..?|swf|ra.?|rm|as.|m4[av]|smi.?)\b/i);
if($is_media_type){
  print "media extension found\n";
}
else{
  print "not a media file\n";
}

This gets the job done without triggering any false positives (at least for the files/urls I've been dealing with so far). Am I missing any obvious types? Do you have a better way to accomplish the same thing? If so, please share in the comments.

● ● ●
Artem Russakovskii is a San Francisco programmer and blogger. Follow Artem on Twitter (@ArtemR) or subscribe to the RSS feed.

In the meantime, if you found this article useful, feel free to buy me a cup of coffee below.