I want to extract a name field from a text eg
name = "My name is John Smith"
should return John Smith
My current code is
grep(".^[A-Z][a-z]+\\s[A-Z][a-z]+", name, value = TRUE)
I want to extract a name field from a text eg
name = "My name is John Smith"
should return John Smith
My current code is
grep(".^[A-Z][a-z]+\\s[A-Z][a-z]+", name, value = TRUE)
We can use sub
to capture the words that start with uppercase, followed by lower case, then a space followed by the word with upper case, lower case letters of the string followed by other characters (.*
) and replace with the backreference (\\1
) of the captured group
sub(".*([A-Z][a-z]+\\s[A-Z][a-z]+).*", "\\1", name)
#[1] "John Smith"
edit: added @DJack's recommendation
name <- c("My name is John Smith")