@MrFlick 有一段非常酷的代码可以处理这样的事情。如果你想要 5 个块
x <- 'ACCACCACCCC'
m <- gregexpr('(?=(.{5}))', x, perl = TRUE)
regcapturedmatches(x, m)[[1]]
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] "ACCAC" "CCACC" "CACCA" "ACCAC" "CCACC" "CACCC" "ACCCC"
或者寻找特定的模式
m <- gregexpr('(ACC[CA])', x, perl = TRUE)
regcapturedmatches(x, m)[[1]]
# [,1] [,2]
# [1,] "ACCA" "ACCC"
函数(source):
regcapturedmatches<-function(x,m) {
if (length(x) != length(m))
stop(gettextf("%s and %s must have the same length",
sQuote("x"), sQuote("m")), domain = NA)
ili <- is.list(m)
useBytes <- if (ili)
any(unlist(lapply(m, attr, "useBytes")))
else
any(attr(m, "useBytes"))
if (useBytes) {
asc <- iconv(x, "latin1", "ASCII")
ind <- is.na(asc) | (asc != x)
if (any(ind))
Encoding(x[ind]) <- "bytes"
}
if (ili) {
if (any(sapply(m, function(x) {is.null(attr(x,"capture.start"))})==T)) {
stop("No capture data found (did you use perl=T?)")
}
starts<-lapply(m, function(x) {attr(x, "capture.start")})
lengths<-lapply(m, function(x) {attr(x, "capture.length")})
} else {
if (is.null(attr(m,"capture.start"))) {
stop("No capture data found (did you use perl=T?)")
}
starts<-data.frame(t(attr(m, "capture.start")))
lengths<-data.frame(t(attr(m, "capture.length")))
}
Substring<-function(x,starts,lens) {
if(all(starts<0)) {
return(character())
} else {
return(t(
mapply(function(x,st,ln) substring(x,st,st+ln-1),
x, data.frame(t(starts)), data.frame(t(lens)),
USE.NAMES=F)
))
}
}
y<-Map(
function(x, sos, mls) {
Substring(x,sos,mls)
},
x,
starts,
lengths,
USE.NAMES = FALSE
)
y
}