5
#!/usr/bin/perl

use strict;
use warnings;
my $string = "praveen is a good boy";
my @try = split(/([a,e,i,o,u]).*\1/,$string);
print "@try\n";

我正在尝试打印给定字符串中包含 2 个相邻元音的所有单词。
o/p : 必须是 "praveen" 和 "good" 。

我尝试使用否定 exp [^] 来拆分并只给出 2 个相邻的元音。

4

3 回答 3

10

Perl 函数split不太适合查找匹配列表。相反,我建议使用正则表达式修饰符g。要处理所有匹配项,您可以循环使用 eg while,也可以一次性分配匹配项列表。

以下示例应匹配字符串中包含两个相邻元音的所有单词:

my $string = "praveen is a good boy"; 
while ( $string =~ /(\w*[aeiou]{2}\w*)/g ) { 
  print "$1\n" 
}

输出:

praveen
good

你也可以这样做:

my @matches = ( $string =~ /\w*[aeiou]{2}\w*/g );

并处理类似于您@try在 OP 中处理的结果。

于 2013-08-18T15:17:02.950 回答
6

你可以做类似..

#!/usr/bin/perl

use strict;
use warnings;

my $str 
   = "praveen is a good boy\n"
   . "aaron is a good boy\n"
   . "praveen and aaron are good, hoot, ho"
   ;

while ($str =~ /(\w*([aeiou])\2(?:\w*))/g) {
       print $1, "\n";
}

正则表达式:

(               group and capture to \1:
 \w*            word characters (a-z, A-Z, 0-9, _) (0 or more times)
   (            group and capture to \2:
    [aeiou]     any character of: 'a', 'e', 'i', 'o', 'u'
   )            end of \2
   \2           what was matched by capture \2
    (?:         group, but do not capture:
      \w*       word characters (a-z, A-Z, 0-9, _) (0 or more times)
    )           end of grouping
)               end of \1

这与做的基本相同/(\w*([aeiou])[aeiou]+(?:\w*))/

输出:

praveen
good
aaron
good
praveen
aaron
good
hoot
于 2013-08-18T15:49:06.987 回答
3
#!/usr/bin/perl

use strict;
use warnings;
my $string = "praveen is a good boy";
my @try = split(/\s/,$string);
for(@try) {
#    if(/[a,e,i,o,u]{2}/) {
    if(/[aeiou]{2}/) { # edited after Birei's comment
        print "$_\n";
    };
};

“split”的第一个参数是分隔符。分裂分裂(-8

于 2013-08-18T15:06:31.223 回答