how to extract exact strings from str_extract?

Viewed 107

I have the a text vector called eventext and I want to extract values from this vector that have "PR" in it. However, when I used this on my real data, I realized that I am also picking up values like "PRESENT" because the word contains "PR" in it.

  library(stringr)
    eventtext<-c("PRESENT","PR-BOND","PR","No BOND")
    str_extract(eventtext,"PR")

Current output is

"PR" "PR" "PR" NA 

What I would want is

NA "PR" "PR" NA 
1 Answers

We can use word boundary so that it won't match the characters inside a word

str_extract(eventtext, "\\bPR\\b")
#[1] NA   "PR" "PR" NA  
Related