flee
flee

Reputation: 1335

Add a period after capital letters followed by a white space

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

Answers (3)

akrun
akrun

Reputation: 887551

Using base R

gsub("(?<=[A-Z])\\s", ". ", v,  perl = TRUE)
#[1] "Smith S. Kohli V. "

data

v <- c("Smith S Kohli V ")

Upvotes: 2

Ronak Shah
Ronak Shah

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

A l w a y s S u n n y
A l w a y s S u n n y

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

Related Questions