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

后端 未结 7 876
执笔经年
执笔经年 2020-12-22 01:32

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

use strict;
use warnings;

my $string1 = \"\'I want to\' \'ex         


        
7条回答
  •  被撕碎了的回忆
    2020-12-22 02:26

    You can try:

    sub extract_quoted {
    
            my ($string, $index) = @_;
            while($string =~ /'(.*?)'/g) {
                    $index--;
                    return $1 if(! $index); # return $1 if index became 0. 
            }
            return; # not found - returns undef or () depending on context.
    }
    

提交回复
热议问题