3

a.

name <- c("Moe Szyslak", "Burns, C. Montgomery", "Rev. Timothy Lovejoy","Ned Flanders" ,"Simpson, Homer" ,"Dr. Julius Hibbert")
require(stringr)
## Loading required package: stringr
require(stringi)
## Loading required package: stringi
revTest<-str_extract_all(name, ",")
i<-1
for (i in 1:length(name)){
  if (revTest[i]== ','){
    name[i]<-paste(str_split_fixed(name[i], ",", 2)[2], str_split_fixed(name[i], ",", 2)[1])
  }
}
name<-stri_trim(name)
name
## [1] "Moe Szyslak"          "C. Montgomery Burns"  "Rev. Timothy Lovejoy"
## [4] "Ned Flanders"         "Homer Simpson"        "Dr. Julius Hibbert"

b.

luTitle<- c("Dr.","Rev.")
titled<-as.logical(str_detect(name,luTitle[2])+str_detect(name,luTitle[1]))
titled
## [1] FALSE FALSE  TRUE FALSE FALSE  TRUE

c.

result<-as.logical(str_count(name," ")-titled-1)
result
## [1] FALSE  TRUE FALSE FALSE FALSE FALSE

7

The assignment fails as it cannot handle the “+” value. The ‘?’ allows for limits to the result. I have provided two solutions.

q7 <- "<title>+++BREAKING NEWS+++</title>"
str_extract(q7, "<.+>")
## [1] "<title>+++BREAKING NEWS+++</title>"
str_sub(q7, end= unlist(str_locate(q7, ">"))[1])
## [1] "<title>"
result<-str_extract(q7, "<.+?>")
result
## [1] "<title>"

8

This is another example of how these regex expressions require a particular ordering of input or they can fail.

theorem <- "(5-3)^2=5^2-2*5*3+3^2 conforms to the binomial theorem."
str_extract(theorem, "[^0-9=+*()]+")
## [1] "-"
result<-str_extract(theorem, "[0-9=+*()-^]+")
result
## [1] "(5-3)^2=5^2-2*5*3+3^2"