Removing multiple spaces and trailing spaces with gsub

How to remove multiple spaces and trailing spaces using only 1 gsub? I already made this function trim <- function(x) gsub(' {2,}',' ',gsub('^ *| *$','',x)) , but I'm trying to rewrite it with only 1 gsub .

In fact, I want to lose weight, how to match something based on the fact that after / before it with gsub. In this example, I need to match all spaces that precede one space, and replace them with "

+6
source share
1 answer

Use a positive lookbehind to see if the current space is preceded by a space:

 ^ *|(?<= ) | *$ 

See here in action: http://regex101.com/r/bJ1mU0

+13
source

All Articles