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

Hi,

I have input like

my $in="foo bar foo bar foo senthil";

If i use this Regular Expression like (a-zA-Z+). I will get output like

foo bar foo bar foo senthil

But I want to get last matches of senthil alone by Regular Expression

Is there any regular Expression for getting last matches

senthil

Replies are listed 'Best First'.
Re: get last matches of the given string
by Ratazong (Monsignor) on Jun 06, 2011 at 08:38 UTC

    With $ you can anchor your RegEx to the end of your input. So try something like

    ([a-zA-Z]+)$
    HTH, Rata

Re: get last matches of the given string
by bart (Canon) on Jun 06, 2011 at 10:43 UTC
    If you use captures in a repeated match (with + or *), then the regex engine will capture the last match. So you can try:
    if($in =~ /(?:\W*(\w+))+/) { print "Last word: $1\n"; }
    With your data, that prints
    Last word: senthil
Re: get last matches of the given string
by Marshall (Canon) on Jun 06, 2011 at 11:55 UTC
    There are a number of ways to do what you want.
    - anchor to the end to get the last word match
    - use list slice to get last or even second to last word
    my ($last) = $in =~ m/(\w+)$/i; print "last=$last\n"; my ($second_to_last) = ($in =~ m/(\w+)/gi)[-2]; #[-1] would have been +last print "second to last=$second_to_last\n"; __END__ Prints: last=senthil second to last=foo
    Note that Perl shortcut of \w also includes _0-9 Often this doesn't matter and I just use the \w instead of making a special set.
Re: get last matches of the given string
by Anonymous Monk on Jun 06, 2011 at 08:26 UTC
    Please post complete code, something that runs, performs some operations, and produces some output.