Matching Wildcard Pattern and Character String in R

Viewed 51

I am trying to count how many times a keyword appears in a string. In the following variable text, I would like to count how many times keyword appears in text. The result should display 3 because AWAY appears twice and WIN appears once in the string.

text<- "AWAYTEAM IS XXX. I THINK THEAWAYTEAM WILL WIN"
keyword<- c("AWAY","WIN")

Any ideas?

2 Answers

We may use str_count with sum

library(stringr)
sum(str_count(text, keyword))
[1] 3

One possibility using stringr

library(stringr)

text<- "AWAYTEAM IS XXX. I THINK THEAWAYTEAM WILL WIN"
keyword<- c("AWAY","WIN")

length(unlist(str_extract_all(text, keyword)))
#> [1] 3

Created on 2021-08-22 by the reprex package (v2.0.0)

Related