Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

regex help

by vijesh (Novice)
on Oct 20, 2014 at 07:01 UTC ( [id://1104378]=perlquestion: print w/replies, xml ) Need Help??

vijesh has asked for the wisdom of the Perl Monks concerning the following question:

Hi Experts, Please help me here. I need to take substring (/fold1/fold2/fold3/) out of following one.

$str1="/fold1/fold2/fold3/file.pl" DB<48> p $str1 /fold1/fold2/fold3/file.pl DB<49> if ($str1 =~ m#([^/]+)$#) { print $1;} file.pl <<<< I managed to get my file name but need to get rest of th +e path. DB<50>

I need to print "/fold1/fold2/fold3/" in fact. what regexp will help me here? -Thanks, Vijesh

Replies are listed 'Best First'.
Re: regex help
by McA (Priest) on Oct 20, 2014 at 07:11 UTC

    Hi,

    if you're interested in getting the directory part of a path name I would suggest using dirname from File::Basename.

    Regards
    McA

      Hello McA,this is working for me..Thanks for support.

Re: regex help
by Athanasius (Archbishop) on Oct 20, 2014 at 07:17 UTC

    Hello vijesh,

    McA is correct, when dealing with filenames and paths a dedicated module will provide a safer and more portable solution than a hand-written regex. But if you still want to use a regex, try this:

    17:12 >perl -wE "my $s = q{/fold1/fold2/fold3/file.pl}; print $1, qq{\ +n} if $s =~ m{^(.+?)[^/]+$}; /fold1/fold2/fold3/ 17:16 >

    This works because the second quantifier is greedy but the first is not.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Hello Athanasius, Thanks for regex. As you said, McA's suggestion also helps. I shall go with Basename api's. -Thanks and Regds, Vijesh

Re: regex help
by choroba (Cardinal) on Oct 20, 2014 at 10:04 UTC
    You can use Path::Tiny to solve most of the file and path related tasks. In this case:
    use Path::Tiny; my $str1 = "/fold1/fold2/fold3/file.pl"; print path($str1)->dirname, "\n";
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      wow.. this is a great help too. -Vijesh

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1104378]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-24 00:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found