Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing multiple spaces and trailing spaces using gsub

Tags:

regex

r

gsub

How can I 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.

Actually, I want lean how to match something based in what is after/before it with gsub. In this example I need to match all spaces that are preceeded by a single space, and replace them by ''

like image 810
Rcoster Avatar asked Feb 06 '13 19:02

Rcoster


1 Answers

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

^ *|(?<= ) | *$

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

like image 109
Joseph Silber Avatar answered Nov 14 '22 23:11

Joseph Silber