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

Hi,
$str = 'C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometest\test12.1x\1'
I need to extract 'fldr3\fldr4\fldr5\test.txt' from this. Can anyone plase guide me to do this?
I need to remove 'C:\fldr1\fld2\' from beging and '@@\main\Msometest\test12.1x\1' from end.
The middle string to be extracted is : 'fldr3\fldr4\fldr5\test.txt'
Thanks, Dan.
  • Comment on Extract middle string from a path using RegExp

Replies are listed 'Best First'.
Re: Extract middle string from a path using RegExp
by toolic (Bishop) on Sep 06, 2008 at 01:31 UTC
    Surely you want a more generic solution than this:
    use strict; use warnings; my $str = 'C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometest\t +est12.1x\1'; my ($str2) = $str =~ /(fldr3\\fldr4\\fldr5\\test.txt)/; print "str2 = $str2\n"; __END__ str2 = fldr3\fldr4\fldr5\test.txt

    If so, please re-phrase your question in more generic terms.

    Also, there is free documentation at: perlretut


      my $str = 'C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometest\t +est12.1x\1';
      Here
      C:\fldr1\fld2\
      is dynamic.
      fldr3\fldr4\fldr5\test.txt
      is also dyanamic.
      Moreover,
      @@\main\Msometest\t +est12.1x\1'
      is dynamic.... Now how can I extract the middle path?
        toolic's point is that it's impossible unless you tell us what special about the indicated points
        | | | | v v C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometest\test12.1x\1

        For instance, how do you know it's not

        | | | | v v C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometest\test12.1x\1

        or

        | | | | v v C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometest\test12.1x\1

        Something has to be static, otherwise you just don't know what to do. How do you decide which components you want?

        Is it the amount of directories up front? If so, first shove off the trailing thing - that's '@@' and what follows, right? Then use File::Spec->splitdir to split the path into components. Remove leading directories. Join the list with File::Spec->catdir.

        use File::Spec; my $goners = 3; # how many? my $str = 'C:\fldr1\fld2\fldr3\fldr4\fldr5\test.txt@@\main\Msometes +t\test12.1x\1'; $str =~ s/\@/\@.*//; my @dirs = File::Spec->splitdir($str); splice @dirs, 0, $goners; print File::Spec->catdir(@dirs);
Re: Extract middle string from a path using RegExp
by ikegami (Patriarch) on Sep 06, 2008 at 01:34 UTC

    Like I said in the CB,

    my $base = 'C:\\fldr1\\fld2\\'; $str =~ s/\@\@.*//s; $str =~ s/^\Q$base\E//;

    or better yet

    use File::Spec::Functions qw( abs2rel ); my $base = 'C:\\fldr1\\fld2'; $str =~ s/\@\@.*//s; $str = abs2rel($str, $base);
      Thanks a lot everyone...