r grepl搜索变量中的多个模式

时间:2015-02-05 17:52:40

标签: regex r pattern-matching grepl

我正在尝试搜索字符串变量,每次找到确定的模式时,搜索功能都会告诉我TRUE。我正在使用grepl找到匹配项:

grepl(pattern,x)

模式需要从几个单词构建,而这些单词又从csv文件中捕获。

我想我在构建模式时做错了,但我找不到错误。

下面是一个虚构的例子

#example file with the string data to classify
des<-c("DDD SS","FFFFF P","AAA EKO BBB","KK SUPER OO","JJ")
num<-c(5,6,2,7,9)
d0<-data.frame(des,num)


#example file with the pattern to search for as rows
t0<-data.frame(c("SUPER","A ISABEL","EKO"))

t1<-as.list(t(t0)) #traspose the vector as la list
t2<-do.call("paste",c(t1,sep="'|'")) #collapse to a single string with '|' (or) symbol for the grepl pattern

cl<-grepl(t2,d0$des)

最终的grepl找不到任何匹配

> cl
[1] FALSE FALSE FALSE FALSE FALSE

有什么建议吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

尝试

 t2 <- paste(t1, collapse="|")
 grepl(t2, d0$des)
#[1] FALSE FALSE  TRUE  TRUE FALSE