在R中是否可以在向量中搜索正则表达式,就好像所有元素都是折叠的单个元素一样?如果我们将所有元素折叠成一个来做这个,那么在搜索之后就不可能将它们放回到它们的元素形式.
这是一个向量.
vector<-c("I","met","a","cow")
假设我的任务是合并搜索字符串所在的两个元素.
所以我期待的是:
vector = "I","Meta","cow"
是否有可能做到这一点?请帮忙.
如果你想要一些匹配“Meta”而不是“taco”的东西,这就可以了:
myFun <- function(vector,word) { D <- "UnLiKeLyStRiNg" ## Construct a string on which you'll perform regex-search xx <- paste0(paste0(D,vector,collapse=""),D) ## Construct the regex pattern start <- paste0("(?<=",D,")") mid <- paste0(strsplit(word,"")[[1]],collapse=paste0("(",")?")) end <- paste0("(?=",")") pat <- paste0(start,mid,end) ## Use it strsplit(gsub(pat,word,xx,perl=TRUE),D)[[1]][-1] } vector <- c("I","cow") myFun(vector,"Meta") # [1] "I" "Meta" "cow" myFun(vector,"taco") # [1] "I" "met" "a" "cow" myFun(vector,"Imet") # [1] "Imet" "a" "cow" myFun(vector,"Ime") # [1] "I" "met" "a" "cow"