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

Hi, I have a file like this Debashis Pranab roy Nagendra roy murali mohan roy and want to print the words that are just before roy expected out put is Pranab Nagendra mohan Can some body help me with this.

Replies are listed 'Best First'.
Re: help with regular exprestion
by jethro (Monsignor) on Mar 15, 2011 at 09:43 UTC
    Check out lookahead patterns (?=...), in your case you would probably need m/(\w+)(?=\s+roy)/g
Re: help with regular exprestion
by moritz (Cardinal) on Mar 15, 2011 at 10:40 UTC
    use 5.010; my @chunks = split " ", "Debashis Pranab roy Nagendra roy murali mohan + roy"; for (1..$#chunks) { say $chunks[$_-1] if $chunks[$_] eq "roy"; }

    Update: change range to start at 1, so that a leading "roy" doesn't result in the last item being printed, as pointed out by jethro++.

Re: help with regular exprestion
by cdarke (Prior) on Mar 15, 2011 at 10:42 UTC
    TMTOWTDI:
    my $str = 'Debashis Pranab roy Nagendra roy murali mohan roy'; my @hits = $str =~ m/\b([[:alpha:]]+)\s+\broy\b/g; print "@hits\n";
    Gives:
    Pranab Nagendra mohan
Re: help with regular exprestion
by umasuresh (Hermit) on Mar 15, 2011 at 13:47 UTC
    I very good tutorial on regular expresions can be found here!