How can I extract the nth occurrence of a match in a Perl regex?

Posted by Zaid on Stack Overflow See other posts from Stack Overflow or by Zaid
Published on 2010-03-31T11:55:06Z Indexed on 2010/03/31 12:13 UTC
Read the original article Hit count: 394

Filed under:
|
|

Is it possible to extract the n'th match in a string of single-quoted words?

use strict;
use warnings;

my $string1 = '\'I want to\' \'extract the word\' \'Perl\',\'from this string\'';
my $string2 = '\'What about\',\'getting\',\'Perl\',\'from\',\'here\',\'?\'';

sub extract_quoted { 

    my ($string, $index) = @_;
    my ($wanted) = $string =~ /some_regex_using _$index/;
    return $wanted;
}

extract_wanted ($string1, 3); # Should return 'Perl', with quotes
extract_wanted ($string2, 3); # Should return 'Perl', with quotes

© Stack Overflow or respective owner

Related posts about perl

Related posts about regex