string<-c(" this is a string ")
是否可以在弦的两侧(或根据需要只是一侧)修剪掉白色空间,并用R中的所需字符替换它?字符串两侧的白色空格数不同,必须在更换时保留.
"~~~~~~~this is a string~~"
解决方法
这似乎是一种低效的方式,但也许你应该朝着gregexpr和regmatches的方向而不是gsub:
x <- " this is a string " pattern <- "^ +?\\b|\\b? +$" startstop <- gsub(" ","~",regmatches(x,gregexpr(pattern,x))[[1]]) text <- paste(regmatches(x,x),invert=TRUE)[[1]],collapse="") paste0(startstop[1],text,startstop[2]) # [1] "~~~~this is a string~~"
## The function replaceEnds <- function(string) { pattern <- "^ +?\\b|\\b? +$" startstop <- gsub(" ",regmatches(string,string))[[1]]) text <- paste(regmatches(string,string),invert = TRUE)[[1]],collapse = "") paste0(startstop[1],startstop[2]) } ## use Vectorize here if you want to apply over a vector vReplaceEnds <- Vectorize(replaceEnds)
一些样本数据:
myStrings <- c(" Four at the start,2 at the end "," three at the start,one at the end ") vReplaceEnds(myStrings) # Four at the start,2 at the end three at the start,one at the end # "~~~~Four at the start,2 at the end~~" "~~~three at the start,one at the end~"