开发者

Perl: How to get all grouped patterns

I have the following code.

Here I am matching the vowels characters words:

if ( /(a)+/ and /(e)+/ and /(i)+/ and /(o)+/ and /(u)+/ )
{
print "$1#$2#$3#$4#$5\n";
$number++;
}

I am trying to get the all matched patterns using grouping, but I am getting only the last expression pattern, which means the fifth expression of the if condition. Here I know that it is giving only 开发者_开发知识库one pattern because last pattern matching in if condition. I want to get all matched patterns, however. Can anyone help me out of this problem?


It is not quite clear what you want to do. Here are some thoughts.

Are you trying to count the number of vowels? In which case, tr will do the job:

    my $count = tr/aeiou// ;
    printf("string:%-20s count:%d\n" , $_ , $count ) ;

output :

    string:book                 count:2
    string:stackoverflow        count:4

Or extract the vowels

    my @array = / ( [aeiou] ) /xg  ;
    print Dumper \@array ;

Output from "stackoverflow question"

    $VAR1 = [
              'a',
              'o',
              'e',
              'o',
              'u',
              'e',
              'i',
              'o'
            ];

Or extract sequences of vowels

    my @array = / ( [aeiou]+ ) /xg  ;
    print Dumper \@array ;

Output from "stackoverflow question"

    $VAR1 = [
              'a',
              'o',
              'e',
              'o',
              'ue',
              'io'
            ];


You could use

sub match_all {
  my($s,@patterns) = @_;

  my @matches = grep @$_ >= 1,
                map [$s =~ /$_/g] => @patterns;

  wantarray ? @matches : \@matches;
}

to create an array of non-empty matches.

For example:

my $string = "aaa e iiii oo uuuuu aa";
my @matches = match_all $string, map qr/$_+/ => qw/ a e i o u /;

if (@matches == 5) {
  print "[", join("][", @$_), "]\n"
    for @matches;
}
else {
  my $es = @matches == 1 ? "" : "es";
  print scalar(@matches), " match$es\n";
}

Output:

[aaa][aa]
[e]
[iiii]
[oo]
[uuuuu]

An input of, say, "aaa iiii oo uuuuu aa" produces

4 matches


  • You have 5 patterns with one matching group () each. Not 1 pattern with 5 groups.
  • (a)+ looks for a string containing a, aa, aaa, aaaa etc.
    The match will be multiple a's, not the word containing the group of a-s.
  • Your if( ...) is true if $_ contains one or more of 'a','e','i','o','u'.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜