ihssan
ihssan

Reputation: 369

Matching words with exactly one vowel

I want to match only the strings that have exactly one vowel.

I tried this code, and it works but it also matches those strings that haven't any vowels (for example hshs, ksks, lslsl) and I need only the strings that have just one vowel

if ( $string !~ /\*w[aeiou]\w*[aeiou]\W*/ ) {
   print $string;
}

Upvotes: 0

Views: 2008

Answers (2)

Borodin
Borodin

Reputation: 126742

You can use tr/// to count the occurrences of letters in a string.

Something like this perhaps

use strict;
use warnings;

for my $string ( qw/ a fare is paid for every cab /) {

  if ( $string =~ tr/aeiuoAEIOU// == 1 ) {
     print $string, "\n";
  }

}

output

a
is
for
cab

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

Make it simple, at least one vowel:

if ($string =~ /[aeiou]/i) {
   print $string;
}

exactly one vowel:

if ($string =~ /^[^aeiou]*[aeiou][^aeiou]*$/i) {
   print $string;
}

Upvotes: 1

Related Questions