如何在 Perl 正则表达式中提取第 n 个匹配项? [英] How can I extract the nth occurrence of a match in a Perl regex?

查看:52
本文介绍了如何在 Perl 正则表达式中提取第 n 个匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从一串单引号中提取nth个匹配项?

Is it possible to extract the nth 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

推荐答案

你可以试试:

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.
}

这篇关于如何在 Perl 正则表达式中提取第 n 个匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆