my_names <- c('a\nb\nc') library(stringr) str_extract(my_names, regex('a.*b.*', dotall=TRUE))