Quick Perl Snippet: Finding If A File Has A Media Extension Using Regex
Friday, March 21st, 2008
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, blogger, and future millionaire (that last part is in the works). 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.

(No Ratings Yet)

beer planet is Artem Russakovskii's blog. Artem is a software engineer at
March 22nd, 2008 at 11:38 am
That code look suspiciously familiar ^_^.
Anyhow, I see that you added Related Posts. Pretty neat isn't it?
December 8th, 2008 at 9:34 pm
Pretty neat code. How many lines should I write the same functionality in cpp. I am a poor cpp guy.