Regexp question...

A

adamomitcheney

Hi All,

Apologies in advance if this is a dumb question ("There are no stupid
questions, but there are loads of inquisitive idiots")...

I wanted a regular expression to seperate a filename from a full path
(UNIX). I came up with the following:

$target =~ m%(.+/)(.+)%;
$targetpath = $1;
$targetfile = $2;

Actually, I expected that not to work; but it does, apparently
perfectly. I thought it would fail because I thought the $1 portion of
the regexp would process $target until it found the leftmost '/' and
then stop, leaving everything else to the $2 part. Why am I wrong? Am I
just feeding it a particularly restrictive set of cases?

What regular expression could I use if I wanted to split a UNIX path
into the bottom level (that is, closest to root) directory and the rest
of the path?

Thanks for your indulgence.

Adam...
 
F

Fabian Pilkowski

I wanted a regular expression to seperate a filename from a full path
(UNIX). I came up with the following:

$target =~ m%(.+/)(.+)%;
$targetpath = $1;
$targetfile = $2;

Actually, I expected that not to work; but it does, apparently
perfectly. I thought it would fail because I thought the $1 portion of
the regexp would process $target until it found the leftmost '/' and
then stop, leaving everything else to the $2 part. Why am I wrong?

In regular expressions ".+" is greedy. Hence the first part process
$target until the *rightmost* slash is found.
What regular expression could I use if I wanted to split a UNIX path
into the bottom level (that is, closest to root) directory and the rest
of the path?

Avoid that greediness. Please read `perldoc perlre` for details.

$target =~ m%(.+?/)(.+)%;

regards,
fabian
 
A

A. Sinan Unur

I wanted a regular expression to seperate a filename from a full path
(UNIX).
I came up with the following:

$target =~ m%(.+/)(.+)%;
$targetpath = $1;
$targetfile = $2;

You do not need the full regex machinery to do accomplish such a
task. In addition, using File::Basename is more appropriate than
rolling your own in this case. See

<URL: http://groups-beta.google.com/group/comp.lang.perl.misc/msg/e8d8519b712c483b?dmode=source>

<URL: http://groups-beta.google.com/groups?q=unur+basename&scoring=d>

Sinan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top