Regex to capture a substring containing punctuation in R

Viewed 41

I have a list of strings where each element contains uppercase names with and without punctuation, followed by a sentence.

names_list = list("MICKEY MOUSE is a Disney character",
                  "DAFFY DUCK is a Warner Bros. character",
                  "GARFIELD, ODI AND JOHN are characters from a USA cartoon comic strip.",
                  "BUGS-BUNNY AND FRIENDS Warner Bros. owns these characters.")

I want to extract only the capitalised names at the start of each string. I got as far as:

library('stringr')
str_extract(names_list, '([:upper:]+([:punct:]?[:upper:]?)[:space:])+')

[1] "MICKEY MOUSE "           "DAFFY DUCK "             "GARFIELD, ODI AND JOHN " "BUNNY AND FRIENDS "

I can't figure out how to specify the mid-word punctuation as in "BUGS-BUNNY" so that I can pull out the whole word. Help much appreciated!

2 Answers

You can try capturing multiple occurrence of upper-case letter along with punctuations and space in them until a space and any upper/lower case letter in encountered.

library(stringr)

str_extract(names_list, '([[:upper:][:punct:][:space:]])+(?=\\s[A-Za-z])')
#[1] "MICKEY MOUSE"     "DAFFY DUCK"    "GARFIELD, ODI AND JOHN" 
#    "BUGS-BUNNY AND FRIENDS"

We can use sub from base R

sub("^([A-Z, -]+)\\s+.*", "\\1", unlist(names_list))
#[1] "MICKEY MOUSE"           "DAFFY DUCK"             "GARFIELD, ODI AND JOHN" "BUGS-BUNNY AND FRIENDS"
Related