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

Regex 使用grepl从模式列表中查找匹配模式,regex,r,string,grepl,Regex,R,String,Grepl,我使用grepl检查字符串是否包含一组模式中的任何模式(我使用“|”分隔模式)。反向搜索没有帮助。如何识别匹配的模式集 其他信息:这可以通过编写循环来解决,但这非常耗时,因为我的集合有>100000个字符串。它能被优化吗 例如:将字符串设为a您正在从packagestringr中查找的stru detect: library(stringr) str_detect(a, pattern) #[1] TRUE TRUE FALSE 如果您有多个字符串,如a=c('hello'、'hola'

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

其他信息:这可以通过编写循环来解决,但这非常耗时,因为我的集合有>100000个字符串。它能被优化吗


例如:将字符串设为
a您正在从package
stringr
中查找的
stru detect

library(stringr)

str_detect(a, pattern)
#[1]  TRUE  TRUE FALSE
如果您有多个字符串,如
a=c('hello'、'hola'、'plouf')
,您可以执行以下操作:

lapply(a, function(u) pattern[str_detect(u, pattern)])

由于模式重叠,您还可以将base R与前瞻表达式一起使用,
(?=)
。使用
gregexpr
可以将每个分组模式的匹配位置提取为矩阵

## changed your string so the second pattern matches twice
a <- "Hellolo"
pattern <- c("ll", "lo", "hl")
pattern1 <- sprintf("(?=(%s))", paste(pattern, collapse=")|(")) #  "(?=(ll)|(lo)|(hl))"

attr(gregexpr(pattern1, a, perl=T)[[1]], "capture.start")
# [1,] 3 0 0
# [2,] 0 4 0
# [3,] 0 6 0
##更改了字符串,使第二个模式匹配两次

a如果我能得到每个元素的所有匹配项,那就太好了。目前我正在迭代所有元素(a),嗯,我不知道是否有函数在这种情况下创建矩阵,我需要阅读文档,这确实很有趣!你的答案比暴力要优化得多。比较:时间间隔为15分钟。蛮力:346次迭代str_detect:87000次以上迭代
## changed your string so the second pattern matches twice
a <- "Hellolo"
pattern <- c("ll", "lo", "hl")
pattern1 <- sprintf("(?=(%s))", paste(pattern, collapse=")|(")) #  "(?=(ll)|(lo)|(hl))"

attr(gregexpr(pattern1, a, perl=T)[[1]], "capture.start")
# [1,] 3 0 0
# [2,] 0 4 0
# [3,] 0 6 0