Reputation: 1335
As the title says, a have a string where I want to add a period after any capital letter that is followed by a whitespace, e.g.:
"Smith S Kohli V "
would become:
"Smith S. Kohli V. "
This is as close as I got:
v <- c("Smith S Kohli V ")
stringr::str_replace_all(v, "[[:upper:]] ", ". ")
"Smith . Kohli . "
I can see I need to add some more code to keep the capital letter, but I can't figure it out, any help much appreciated.
Upvotes: 1
Views: 221
Reputation: 887551
Using base R
gsub("(?<=[A-Z])\\s", ". ", v, perl = TRUE)
#[1] "Smith S. Kohli V. "
v <- c("Smith S Kohli V ")
Upvotes: 2
Reputation: 389175
Base R using gsub
:
v <- c("Smith S Kohli V ")
gsub('([A-Z])\\s', '\\1. ', v)
#[1] "Smith S. Kohli V. "
Upvotes: 4
Reputation: 38542
You can do this way to capture that match where the capital letter followed by space(
) character and then replace the whole match with an extra dot(.)
.
v <- c("Smith S Kohli V ")
stringr::str_replace_all(v, "([A-Z](?= ))", "\\1.")
Regex: https://regex101.com/r/uriEYS/1
Demo: https://rextester.com/ELKM47734
Upvotes: 4