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

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -