问题
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 ''
回答1:
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
来源:https://stackoverflow.com/questions/14737266/removing-multiple-spaces-and-trailing-spaces-using-gsub