8

是否可以在 R 中搜索向量中的正则表达式,就好像所有元素都是折叠的单个元素一样?如果我们将所有元素折叠成一个来做到这一点,那么在搜索之后就不可能将它们恢复为元素形式。

这是一个向量。

vector<-c("I", "met", "a", "cow")

现在,搜索词是“meta”(元素 2 和 3 已折叠)。

假设我的任务是合并搜索字符串所在的两个元素。

所以我期望的是:

vector = "I", "meta", "cow"

是否有可能做到这一点?请帮忙。

4

3 回答 3

5

如果您想要匹配"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("(", D, ")?"))
    end <- paste0("(?=", D, ")")
    pat <- paste0(start, mid, end)

    ## Use it
    strsplit(gsub(pat, word, xx, perl=TRUE), D)[[1]][-1]
}

vector <- c("I", "met", "a", "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"
于 2012-09-03T23:16:14.730 回答
3

如果只合并完整的元素,您可以尝试这种方法:

mergeRegExpr <- function(x, pattern) {
    str <- paste(x, sep="", collapse="")

    ## find starting position of each word
    wordStart <- head(cumsum(c(1, nchar(x))), -1)

    ## look for pattern
    rx <- regexpr(pattern=pattern, text=str, fixed=TRUE)

    ## pos of matching pattern == rx+nchar(pattern)-1
    rxEnd <- rx+attr(rx, "match.length")-1

    ## which vector elements doesn't match pattern
    sel <- wordStart < rx | wordStart > rxEnd

    ## insert merged elements
    return(append(x[sel], paste(x[!sel], collapse=""), rx-1))
}

vector <- c("I", "met", "a", "cow")

mergeRegExpr(vector, "meta")
# "I"    "meta" "cow"
mergeRegExpr(vector, "acow")
# "I"    "met"  "acow"
mergeRegExpr(vector, "Imeta")
# "Imeta" "cow"

## partial matching doesn't work    
mergeRegExpr(vector, "taco")
# "I"       "metacow"
于 2012-09-03T17:52:22.113 回答
2

基于 Carl Witthoft 的评论,我的解决方案不是使用正则表达式,而是使用基本匹配:

# A slightly longer vector
v = c("I", "met", "a", "cow", "today",
      "You", "met", "a", "cow", "today")

# Create the combinations of each pair
temp1 = sapply(1:(length(v)-1), 
               function(x) paste0(v[x], v[x+1]))

# Grab the index of the desired search term
temp2 = which(temp1 %in% "meta")
# The following also works.
# Don't know what's faster/better.
# temp2 = grep("meta", temp1)

# Do some manual substitution and deletion
v[temp2] <- "meta"
v <- v[-(temp2+1)]

我认为这根本不是一个理想的情况。

于 2012-09-03T17:27:30.477 回答