首页 > 解决方案 > 如何列出包含给定模式的字符串?

问题描述

我有三个字符串,其中包含什么,何时,为什么,如下所示

  1. 你叫什么名字
  2. 什么时候以及为什么要跑高速
  3. 你父亲叫什么名字

有没有办法列出所有包含给定模式的字符串。

首先我检测到模式,然后计算真值的数量

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

我希望输出的方式

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

标签: rregexstringr

解决方案


我们可以创建一个向量来搜索并使用sapply它来查找它是否存在于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所以忽略这种情况"What"并且"what"是相同的。

"\\b"为每个添加单词边界 ( ),tag以便"what"与 不匹配"whatever"

数据

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")

推荐阅读