Regex Pattern to Find Palindrome-Like Names with Specific Constraints in R

Another way could be

library(dplyr)
#install.packages("babynames")
library(babynames)
library(stringi)
library(stringr)
data(babynames)

babynames %>% 
  filter(nchar(name)==7) %>% # filter namee length first for speed
  filter(substr(tolower(name),1,3) == substr(stri_reverse(name),1,3) & 
           str_detect(substr(tolower(name),4,4),"[aeiou]"))

One could also use (?i) in the regex to make it insensitive to cases:

babynames %>%
  filter(str_detect(name, "^([a-zA-Z])([a-zA-Z])([a-zA-Z])(?i)[aeiou]\\3\\2\\1$"))

Or tolower(), but that’s a bit slower:

babynames %>%
  filter(str_detect(tolower(name), "^([a-zA-Z])([a-zA-Z])([a-zA-Z])(?i)[aeiou]\\3\\2\\1$"))

Read more here: Source link