#!/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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With