regex - Remove trailing and leading spaces and extra internal whitespace with one gsub call -
i know can remove trailing , leading spaces
gsub("^\\s+|\\s+$", "", x)
and can remove internal spaces with
gsub("\\s+"," ",x)
i can combine these 1 function, wondering if there way 1 use of gsub
function
trim <- function (x) { x <- gsub("^\\s+|\\s+$|", "", x) gsub("\\s+", " ", x) } teststring<- " test. " trim(teststring)
here option:
gsub("^ +| +$|( ) +", "\\1", teststring) # frank's input, , agstudy's style
we use capturing group make sure multiple internal spaces replaced single space. change " " \\s
if expect non-space whitespace want remove.
Comments
Post a Comment