Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex to grab file extension 1

Status
Not open for further replies.

LawnBoy

MIS
Mar 12, 2003
2,881
I'm trying to extract a file extension (.any) and populate a scalar with it. I've got 4 possible situations and I can't come up with a regex that matches in all situations.
I've got:
1 - somefile.txt
2 - some.file.txt
3 - somefile..text (don't ask, my users will type in anything for a filename)
4 - somefile

After browsing this and other forums, I came up with (filename is in $_)
Code:
($name, $ext) = (/^(.*?)\.?([^\.]*)$/);
This works great for situations 1, 2, and 3, but in situation 4 I end up with $name = null and $ext="somefile". What I did was to throw in an extra check:
Code:
($name, $ext) = (/^(.*?)\.?([^\.]*)$/);
if ($name eq '') {
	$ext = '';
}
This works well enough, but it's ugly code.
How can I meet all requirements with a single regex?
 
In the second example you've posted, what do you want to be returned as the extension? `file.txt' or `.txt'. The reason I ask is because for gzipped tarballs, the extension is `.tar.gz', in which case just grabbing the text after the last dot isn't enough.
 
Good point. I want to end up with ".ext" or "ext". In your example I would need ".tar.gz" or "tar.gz".

So make that 5 conditions to meet.
 
use the FIle::Basename module, but this is still "messy" when dealing with incorrectly or oddly named files.
 
Another question, has anybody ever seen a file ending in ".gz" that isn't ".tar.gz"? If not, I can slop my way around that too.
 
Code:
[b]#!/usr/bin/perl[/b]

while (<DATA>) {
  print "$1\n" if m/((\.tar)?\.[a-z]+)$/;
}

[blue]__DATA__
somefile.txt
some.file.txt
somefile..text
somefile.tar.gz
somefile[/blue]

Kind Regards
Duncan
 
That works nicely Duncan, thx. I'm gonna have to get a good book on regex's...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top