我正在寻找拆分通用形式的字符串,其中方括号表示字符串的“部分”。前任:
x <- "[a] + [bc] + 1"
并返回一个看起来像这样的字符向量:
"[a]" " + " "[bc]" " + 1"
编辑:最终使用这个:
x <- "[a] + [bc] + 1"
x <- gsub("\\[",",[",x)
x <- gsub("\\]","],",x)
strsplit(x,",")
我看过 TylerRinker 的代码并怀疑它可能比这更清楚,但这可能是学习一组不同功能的方式。(在我注意到它在空格上拆分之前,我更喜欢他。)我尝试调整它以使其工作,strsplit
但该功能总是删除分隔符。也许这可以调整为newstrsplit
在分隔符处分裂但将它们留在里面?可能不需要在第一个或最后一个位置拆分并区分打开和关闭分隔符。
scan(text= # use scan to separate after insertion of commas
gsub("\\]", "],", # put commas in after "]"'s
gsub(".\\[", ",[", x)) , # add commas before "[" unless at first position
what="", sep=",") # tell scan this character argument and separators are ","
#Read 4 items
#[1] "[a]" " +" "[bc]" " + 1"
这是一种懒惰的方法:
FUN <- function(x) {
all <- unlist(strsplit(x, "\\s+"))
last <- paste(c(" ", tail(all, 2)), collapse="")
c(head(all, -2), last)
}
x <- "[a] + [bc] + 1"
FUN(x)
## > FUN(x)
## [1] "[a]" "+" "[bc]" " +1"
您可以手动计算分割点并使用substring
:
split.pos <- gregexpr('\\[.*?]',x)[[1]]
split.length <- attr(split.pos, "match.length")
split.start <- sort(c(split.pos, split.pos+split.length))
split.end <- c(split.start[-1]-1, nchar(x))
substring(x,split.start,split.end)
# [1] "[a]" " + " "[bc]" " + 1"
这是一个在括号上拆分并将它们保留在结果中的版本,使用积极的前瞻和后瞻:
splitme <- function(x) {
x <- unlist(strsplit(x, "(?=\\[)", perl=TRUE))
x <- unlist(strsplit(x, "(?<=\\])", perl=TRUE))
for (i in which(x=="[")) {
x[i+1] <- paste(x[i], x[i+1], sep="")
}
x[-which(x=="[")]
}
splitme(x)
#[1] "[a]" " + " "[bc]" " + 1"