How does one do str_replace
with a "starting with" ^
and a vector?
I am trying to remove the prefixes (Mr., Ms., Dr., Capt., etc.) from a list of names, only from the beginning. I have tried: str_replace(name, prefix, '')
. This replaces only a few of the prefixes (Mr., Ms., Dr., Capt., etc.) from the vector of names but most prefixes are still present. At the same time I don't want to replace the Dr in say Dr. Drake
to ake
. Dr. Drake
should be Drake
.
name <- c('Mrs. Emily S', 'Dr. Richard L', 'Dr. Drake D', 'Mr. Mrdrmsmrs', 'Test Name')
prefix <- c('Dr.', 'Mr.', 'Ms.', 'Mrs.', 'Capt.')
# Wiktor Stribiżew's code
str_replace(name, paste0("^(?:", paste(prefix, collapse="|"), ")(?!\\.)"), '')
There are whitespaces. However we can remove those with trimws()
or stringr::str_trim()