How to use regex to remove spaces before, between, and after strings in R

Viewed 30

I have a string that looks like this:

string <- "     id1 id2     id3 "

I would like to remove any spaces at the beginning, the end, and between two ids such that any two ids are separated by a single space:

"id1 id2 id3"

I tried

> gsub("\\ ", "", string) 
[1] "id1id2id3"

That removed spaces before and after just fine, but also removed the one in between two ids.

0 Answers
Related