Merge Multiple spaces to single space; remove trailing/leading spaces

CKM picture CKM · Sep 7, 2014 · Viewed 52.1k times · Source

I want to merge multiple spaces into single space(space could be tab also) and remove trailing/leading spaces.

For example...

string <- "Hi        buddy        what's up    Bro" 

to

"Hi buddy what's up bro"

I checked the solution given at Regex to replace multiple spaces with a single space. Note that don't put \t or \n as exact space inside the toy string and feed that as pattern in gsub. I want that in R.

Note that I am unable to put multiple space in toy string. Thanks

Answer

Rich Scriven picture Rich Scriven · Sep 7, 2014

This seems to meet your needs.

string <- "  Hi buddy   what's up   Bro "
library(stringr)
str_replace(gsub("\\s+", " ", str_trim(string)), "B", "b")
# [1] "Hi buddy what's up bro"