Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 966
CKM Avatar asked Sep 07 '14 06:09

CKM


People also ask

How do you delete multiple spaces with a single space in a string?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do I remove extra spaces in R?

trimws() function in R Language is used to trim the leading white spaces. It shrinks an object by removing outermost rows and columns with the same values.


1 Answers

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" 
like image 107
Rich Scriven Avatar answered Sep 19 '22 16:09

Rich Scriven