djMohit
djMohit

Reputation: 171

How to list out string which contain a given pattern?

I have three strings which contain what , when , why as given below

  1. What is your name
  2. When and why should you run for high speed
  3. What is your father name

Is there a way to list out all string which contain the given pattern.

First i detected for the pattern and then counted the number of True values

e<-str_detect(c, "What")
   length(e[e == TRUE])

I expect the output in the way

Number of string contain What: 02 
Number of String contain when : 01
Number of String contain why : 01

Upvotes: 1

Views: 439

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389265

We could create a vector to search for and use sapply to find if it is present in a string

vals <- colSums(sapply(tags, function(x) 
        grepl(paste0("\\b",x, "\\b"), strings, ignore.case = TRUE)))
vals

#what when  why 
#   2    1    1 

ignore.case ignores the case so "What" and "what" is the same.

Word boundary ("\\b") is added for each tag so that "what" does not match with "whatever".

data

strings <- c("What is your name", "When and why should you run for high speed",
             "What is your father name ")
tags <- c("what", "when", "why")

Upvotes: 3

Related Questions