How to get rid of the repetitive commas of a R string

Viewed 65

I have an R string looks like:

0B5P4ZZ, 0B9P40Z, , , , , , , , , , , , , , , , , , , , , , , , , , , ,

How can I get rid of the space-commas at the end of this string so that it looks like the following?

0B5P4ZZ, 0B9P40Z

Thanks!

5 Answers

Another solution:

str_remove_all(s, "(, )+$")
trimws(text, whitespace = '[, ]+')
[1] "0B5P4ZZ, 0B9P40Z"
stringr::str_replace('0B5P4ZZ, 0B9P40Z, , , , , , , , , , , , , , , , , , , , , , , , , , , , ', '(.*[A-Z]).*', '\\1')
[1] "0B5P4ZZ, 0B9P40Z"

If you never expect to have any important text after repeated commas, you can just delete everything after ", ,":

> x <- "0B5P4ZZ, 0B9P40Z, , , , , , , , , , , , , , , , , , , , , , , , , , , , "
> gsub(", ,.*","",x)
[1] "0B5P4ZZ, 0B9P40Z"

If you may have important values at the end of the string, you have to use more creative regex:

> x <- "0B5P4ZZ, 0B9P40Z, , , , , , , , , , , , , , , , , , , 0B9P40Z"
> gsub("(, ){2,}",", ",x)
[1] "0B5P4ZZ, 0B9P40Z, 0B9P40Z"

(, ) means match ", "; {2,} means only match (, ) if you see it repeat at least twice consecutively.

Just to add to the other great answers, this is a nice use case for a recursive function, though not particularly efficient.

get_rid_of_commas <- function(the_string) {
  
  if(substr(the_string, nchar(the_string) - 1, nchar(the_string)) == ', ')
    return(get_rid_of_commas(substr(the_string, 1, nchar(the_string) - 2 )))
  else
    return(the_string)
}

> get_rid_of_commas("0B5P4ZZ, 0B9P40Z, , , , , , , , , , , , , , , , , , , , , , , , , , , , ")      
[1] "0B5P4ZZ, 0B9P40Z"
Related