Find words with at most two vowels

Viewed 84

I have made a function to search words which have two vowels together. The function give me the vowels together (for example: ee, ou), but I need the complete word (tree, four).

lt <- c("tree", "four", "hello", "play")

vowel <- function(x) {  
  a<- regexpr(pattern = "[aeiou]{2}", x) 
    regmatches(x, a)
}

vowel(lt)

# [1] "ee" "ou"

Thank you in advance

4 Answers

We can simply use grepl which in my opinion is more user friendly.

vowel <- function(x) 
   
 {  
   a<- grepl("[aeiou]{2}", x) 
   x[a]
 }
 vowel(lt)
[1] "tree" "four"

Another way is to replace

[aeiou]{2}

with

\w*[aeiou]{2}\w*

to include the letters before and after the double vowel in the word.

Here is solution with stringr:

library(stringr)

lt[str_count(lt, '[^aeiou]') ==2]
[1] "tree" "four"

The regexpr returns -1 if there is no match. Therefore, instead of using regmatches, the index itself can be used to subset if we convert to logical

lt[regexpr("[aeiou]{2}", lt) >0]
[1] "tree" "four"
Related