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

标签 regex r string 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

最佳答案

您正在寻找 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/

相关文章:

php - 在SQL查询中插入字符串以更改PHP的顺序

mysql - MySql 正则表达式等价于什么

r - R lda 包中 lda.collapsed.gibbs.sampler 命令的输出

c - 在C中构建很长的重复字符串

r - 字符串分割的模式如何成为子字符串本身?

sql - 不区分大小写的搜索/查询

r - 如何重现置信区间图?

r - 如何为具有百分比的多个变量创建堆叠条形图

字符串连接的 C++ 开销

c++ - 从旧字符串创建新字符串