如何通过模式匹配提取单词?

Ang*_*gus 5 perl

#!/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";
Run Code Online (Sandbox Code Playgroud)

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

我尝试使用否定exp [^]来分割并仅给出2个相邻的元音.

Nei*_*ter 10

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

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

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

输出:

praveen
good
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

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

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


hwn*_*wnd 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";
}
Run Code Online (Sandbox Code Playgroud)

正则表达式:

(               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
Run Code Online (Sandbox Code Playgroud)

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

输出:

praveen
good
aaron
good
praveen
aaron
good
hoot
Run Code Online (Sandbox Code Playgroud)