suppressPackageStartupMessages(library("tidyverse"))
package 㤼㸱tidyverse㤼㸲 was built under R version 3.6.3

1. For each of the following challenges, try solving it by using both a single regular expression, and a combination of multiple str_detect() calls.

Find all words that start or end with x. Find all words that start with a vowel and end with a consonant. Are there any words that contain at least one of each different vowel? The answer to each part follows.

1. Find all words that start or end with x.

# one regex
words[str_detect(words, "^x|x$")]
[1] "box" "sex" "six" "tax"
# split regex into parts
start_with_x <- str_detect(words, "^x")
end_with_x <- str_detect(words, "x$")
words[start_with_x | end_with_x]
[1] "box" "sex" "six" "tax"

2. Find all words that start with a vowel and end with a consonant.

str_subset(words, "^[aeiou].*[^aeiou]$") %>% head()
[1] "about"   "accept"  "account" "across"  "act"     "actual" 
start_with_vowel <- str_detect(words, "^[aeiou]")
end_with_consonant <- str_detect(words, "[^aeiou]$")
words[start_with_vowel & end_with_consonant] %>% head()
[1] "about"   "accept"  "account" "across"  "act"     "actual" 

3. Are there any words that contain at least one of each different vowel?

There is not a simple regular expression to match words that that contain at least one of each vowel. The regular expression would need to consider all possible orders in which the vowels could occur.

pattern <-
  cross(rerun(5, c("a", "e", "i", "o", "u")),
    .filter = function(...) {
      x <- as.character(unlist(list(...)))
      length(x) != length(unique(x))
    }
  ) %>%
  map_chr(~ str_c(unlist(.x), collapse = ".*")) %>%
  str_c(collapse = "|")

To check that this pattern works, test it on a pattern that should match

str_subset("aseiouds", pattern)
[1] "aseiouds"

Using multiple str_detect() calls, one pattern for each vowel, produces a much simpler and readable answer.

str_subset(words, pattern)
character(0)
words[str_detect(words, "a") &
  str_detect(words, "e") &
  str_detect(words, "i") &
  str_detect(words, "o") &
  str_detect(words, "u")]
character(0)

There appear to be none.

2. What word has the higher number of vowels? What word has the highest proportion of vowels? (Hint: what is the denominator?)

The word with the highest number of vowels is

vowels <- str_count(words, "[aeiou]")
words[which(vowels == max(vowels))]
[1] "appropriate" "associate"   "available"   "colleague"   "encourage"   "experience" 
[7] "individual"  "television" 

The word with the highest proportion of vowels is

prop_vowels <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