Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the words through pattern matching?

Tags:

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";

I am trying to print all words containing 2 adjacent vowels in a given string.
o/p : has to be "praveen" and "good" .

I tried with the negate exp [^] to split and give only the 2 adjacent vowels.

like image 816
Angus Avatar asked Aug 18 '13 14:08

Angus


2 Answers

The Perl function split isn't a great fit for finding a list of matches. Instead, I would recommend using the regex modifier g. To process all the matches, you can either loop, using e.g. while, or you can assign the list of matches in one go.

The following example should match all words in a string which contain two adjacent vowels:

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

Output:

praveen
good

You could also do this:

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

and process the result similar to how you were processing @try in the OP.

like image 88
Neil Slater Avatar answered Oct 08 '22 04:10

Neil Slater


You could do something like..

#!/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";
}

Regular expression:

(               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

Which is basically the same as doing /(\w*([aeiou])[aeiou]+(?:\w*))/

Output:

praveen
good
aaron
good
praveen
aaron
good
hoot
like image 26
hwnd Avatar answered Oct 08 '22 04:10

hwnd