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 strongm 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 name from path?

Status
Not open for further replies.

ericse

Programmer
Apr 19, 2007
32
US
Hi guys-

Here's what I have thus far:

Code:
#!/usr/bin/perl

use strict;
my $var = 'C:\Documents and Settings\blah\File-Upload1.doc';
$var = ($var =~ /\\([\w\- ]+\.[\w]+)$/) ? $1 : $var;
print "$var\n";

Everything works. The only problem is *special* characters. If I add in support for all the characters, it grabs the whole string (minus C:\).........I can't seem to figure this out. Any help would be greatly appreciated. BTW, I can't use the Find::File, or File::Basename modules--this needs to be done via a regex. Thanks again


~Eric
 
one possible way:

Code:
$var = ($var =~ /\\([^\]+)$/) ? $1 : $var;


------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
change: [^\]
to: [^\\]

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Thanks Kevin. I also made it work for *nix file systems as well:

Code:
$name = ($name =~ /[\\\/]([^\\\/]+)$/) ? $1 : $name;

:) Thanks again,

~Eric
 
[smile]

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Hi Eric,

Even if you "can't use" core libraries like File::Basename, you still have the option to look at the source of this packages to determine what logic they use.


File::Basename also uses regular expressions, so just take a look at the file_parse subroutine to learn about the different Operating Systems that it supports. There is always a Source link at the top of CPAN doc pages that comes in handle for quick inspections.

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top