in reply to Capturing the nth word in a string

Perhaps since you're only interested in one 'word' you could save Perl the bother of capturing all of them:

print ( $str =~ /(?:\w+\W+){3}(\w+)/ ), "\n";

Of course having n (3 in this case) buried inside the regex doesn't exactly make for a general solution.

Replies are listed 'Best First'.
Re: Re: Capturing the nth word in a string
by Jasper (Chaplain) on Oct 14, 2003 at 13:20 UTC
    You don't have to hard code the '3' here. It can easily be a variable. This is a good solution.
Re: Re: Capturing the nth word in a string
by Roger (Parson) on Oct 14, 2003 at 23:09 UTC
    Yes! Indeed this is an excellent solution. Thanks for the efford, I will write it down somewhere for future reference. :-)

    my ($nth) = $str =~ /(?:\w+\W+){3}(\w+)/; # capture 4th word