This question is very similar to Removing multiple spaces and trailing spaces using gsub, except that I'd like to apply it to commas instead of spaces.
For example, I'd like a function TrimCommas
to turn x
into y
:
x <- c("a,b,c", ",a,b,,c", ",,,a,,,b,c,,,")
# y <- TrimCommas(x) # presumably
y <- c("a,b,c", "a,b,c", "a,b,c")
The solution for spaces was gsub("^ *|(?<= ) | *$", "", x, perl=T)
, so I'm hoping comparing the solution for this will help explain some regex fundamentals as well.