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
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With