How to extract everything occurring after a character and before the last occurrence of another character in R?

Viewed 65

I have three strings as shown below:

"GO:0016559~peroxisome fission,"
"GO:0006122~mitochondrial electron transport, ubiquinol to cytochrome c,"
"GO:0006122~mitochondrial electron transport, ubiquinol to cytochrome c,GO:0006334~nucleosome assembly,"

How do I extract all occurrences of substrings after "~" and before "," (which is either the end of the string or is succeeded by GO:.........,)?

Desired output:

"peroxisome fission"
"mitochondrial electron transport, ubiquinol to cytochrome c"
"mitochondrial electron transport, ubiquinol to cytochrome c" "nucleosome assembly"

This is to be achieved in one generalised statement in R.

I tried using this:

strapplyc(str, "[~](.*?)[,]", simplify = c)

(where str is a variable which stores each of the three strings, one at a time, in a loop)

But the output I got is:

"peroxisome fission"
"mitochondrial electron transport"
"mitochondrial electron transport" "nucleosome assembly"
2 Answers

In base R, you could do:

sub(".*~",'', grep("~",t(read.csv(text = s, header = FALSE)), value = TRUE))
[1] "peroxisome fission"               "mitochondrial electron transport"
[3] "mitochondrial electron transport" "nucleosome assembly"      

     

You can use

(?<=~).*?(?=,(?:GO:\d+~|$))

See the regex demo. Details:

  • (?<=~) - a location right after ~ char
  • .*? - any zero or more chars other than line break chars, as few as possible
  • (?=,(?:GO:\d+~|$)) - a positive lookahead that requires a comma and then either GO:, one or more digits and ~ or end of string immediately to the right of the current location.

See an R demo:

> library(stringr)
> x <- c("GO:0016559~peroxisome fission,","GO:0006122~mitochondrial electron transport, ubiquinol to cytochrome c,","GO:0006122~mitochondrial electron transport, ubiquinol to cytochrome c,GO:0006334~nucleosome assembly,")
> unlist(str_extract_all(x, "(?<=~).*?(?=,(?:GO:\\d+~|$))"))
[1] "peroxisome fission"                                         
[2] "mitochondrial electron transport, ubiquinol to cytochrome c"
[3] "mitochondrial electron transport, ubiquinol to cytochrome c"
[4] "nucleosome assembly"    
Related