是否可以在一串单引号词中提取第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. }