Removing multiple commas and trailing commas using gsub

后端 未结 1 635
情深已故
情深已故 2021-01-01 01:24

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,

相关标签:
1条回答
  • 2021-01-01 02:07

    Isn't the solution pretty similar?

    x <- c("a,b,c", ",a,b,,c", ",,,a,,,b,c,,,")
    gsub("^,*|(?<=,),|,*$", "", x, perl=T)
    # [1] "a,b,c" "a,b,c" "a,b,c"
    

    There are three parts to the regex ^,*|(?<=,),|,*$:

    • ^,* -- this matches 0 or more commas at the beginning of the string
    • (?<=,), -- this is a positive lookbehind to see if there a comma behind a comma, so it matches , in ,,
    • ,*$ -- this matches 0 or more commas at the end of the string

    As you can see all of the above are substituted with nothing.

    You can make this generic to any character (" ", ",", etc.) with this function:

    TrimMult <- function(x, char=" ") {
      return(gsub(paste0("^", char, "*|(?<=", char, ")", char, "|", char, "*$"),
                  "", x, perl=T))
    }
    
    0 讨论(0)
提交回复
热议问题