如何在Perl正则表达式中提取第n个匹配项?

前端之家收集整理的这篇文章主要介绍了如何在Perl正则表达式中提取第n个匹配项?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在一串单引号词中提取第n个匹配?
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,with quotes

解决方法

你可以试试:
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.
}
原文链接:https://www.f2er.com/Perl/172378.html

猜你在找的Perl相关文章