我使用 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
最佳答案
您正在寻找 str_detect
来自包裹 stringr
:
library(stringr)
str_detect(a, pattern)
#[1] TRUE TRUE FALSE
如果您有多个字符串,例如
a = c('hello','hola','plouf')
你可以做:lapply(a, function(u) pattern[str_detect(u, pattern)])
关于regex - 使用 grepl 从模式列表中查找匹配模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31564178/