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

I was wondering what the best way to find text between two strings would be in a variable...

for example I want to extract cat from the following:
foocatbar

but the next time it may be:
foodogbar
(so I would want to extract dog)

thanks in advanced!

Replies are listed 'Best First'.
Re: Find text between two strings?
by Joost (Canon) on Jul 12, 2005 at 16:22 UTC
Re: Find text between two strings?
by fmerges (Chaplain) on Jul 12, 2005 at 16:27 UTC

    Hi,

    As Joost said, read the tutorial and also perlre.

    Using word boundaries should be a addon, so:

    my ($thing) = $input =~ /\bfoo(.*?)bar\b/;

    Regards,

    |fire| at irc.freenode.net

    I like merlyn's disclaimer

Re: Find text between two strings?
by calin (Deacon) on Jul 12, 2005 at 21:21 UTC

    Consider the following string:

    foofooxxxbarbar

    Then what constitutes the text between "foo" and "bar"?

    • xxx
    • fooxxxbar
    • fooxxx
    • xxxbar
    • ?
Re: Find text between two strings?
by artist (Parson) on Jul 12, 2005 at 16:24 UTC
    ($variable) = $string =~ /foo(.*?)bar/;
    --Artist
Re: Find text between two strings?
by Smylers (Pilgrim) on Jul 12, 2005 at 16:25 UTC
    foreach (qw<foocatbar foodogbar foonullooops>) { if (/foo(.*)bar/) { print "$1\n"; } else { print "not found in $_\n"; } }

    Smylers