使用grepl从模式列表中查找匹配的模式

Nav*_*hew 4 regex string r grepl

我使用grepl检查一个字符串是否包含一组模式中的任何模式(我使用'|'来分隔模式).反向搜索没有帮助.如何识别匹配的模式集?

附加信息:这可以通过编写循环来解决,但由于我的集合具有> 100,000个字符串,因此非常耗时.可以优化吗?

例如:让字符串为 a <- "Hello"

pattern <- c("ll", "lo", "hl")

pattern1 <- paste(pattern, collapse="|") # "ll|lo|hl"

grepl(a, pattern=pattern1) # returns TRUE

grepl(pattern, pattern=a) # returns FALSE 'n' times - n is 3 here
Run Code Online (Sandbox Code Playgroud)

Col*_*vel 7

您正在寻找str_detect包装stringr:

library(stringr)

str_detect(a, pattern)
#[1]  TRUE  TRUE FALSE
Run Code Online (Sandbox Code Playgroud)

如果您有多个字符串,就像a = c('hello','hola','plouf')您可以这样做:

lapply(a, function(u) pattern[str_detect(u, pattern)])
Run Code Online (Sandbox Code Playgroud)