This seems like an inefficient way to do this, but perhaps you should look in gregexpr
and regmatches
instead of gsub
:
x <- " this is a string " pattern <- "^ +?\\b|\\b? +$" startstop <- gsub(" ", "~", regmatches(x, gregexpr(pattern, x))[[1]]) text <- paste(regmatches(x, gregexpr(pattern, x), invert=TRUE)[[1]], collapse="") paste0(startstop[1], text, startstop[2])
And, for fun, as a function and a "vectorized" function:
## The function replaceEnds <- function(string) { pattern <- "^ +?\\b|\\b? +$" startstop <- gsub(" ", "~", regmatches(string, gregexpr(pattern, string))[[1]]) text <- paste(regmatches(string, gregexpr(pattern, string), invert = TRUE)[[1]], collapse = "") paste0(startstop[1], text, startstop[2]) } ## use Vectorize here if you want to apply over a vector vReplaceEnds <- Vectorize(replaceEnds)
Some sample data:
myStrings <- c(" Four at the start, 2 at the end ", " three at the start, one at the end ") vReplaceEnds(myStrings)
source share