Home: Perl Programming Help: Regular Expressions:
Parsing a path



bes7252
Deleted

Nov 27, 2000, 1:42 PM


Views: 4156
Parsing a path

I have the string c:\temp\abc\def and I need to know the position of the right-most '\' character. I can get the left-most by using =~ and then $-[0]. How do I get the right-most though?

Thanks!
Brian


japhy
Enthusiast / Moderator

Nov 27, 2000, 2:50 PM


Views: 4156
Re: Parsing a path

Don't use a regex for this. Use the rindex() function -- it's better suited for the task:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$path = 'c:\users\jeffp\file.txt'; # eww, backslashes are bad
$last_slash = rindex($path, '\\');
$filename = substr($path, $last_slash + 1);
print $filename; # file.txt
</pre><HR></BLOCKQUOTE>

If you really want to use regexes, I'd suggest:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


($filename) = $path =~ /([^\\]*)$/;
</pre><HR></BLOCKQUOTE>

That matches the last set of non-\ characters in $path, and stores them in $filename.

------------------
Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher