r - gsub on last special character


Keywords:r 


Question: 

I want to get two strings that occurs before and after last special character (i.e. _).

one <- c("TRANS-PLATINUM_(II)_DIAMMINE_DICHLORIDE_kidney")

I expect result

string1 = TRANS-PLATINUM_(II)_DIAMMINE_DICHLORIDE

string2 = kidney

1 Answer: 

We can use

scan(text=sub("(.*)_([^_]+)$", "\\1,\\2", one), sep=",", what ='', quiet = TRUE)
#[1] "TRANS-PLATINUM_(II)_DIAMMINE_DICHLORIDE" "kidney"   

Or using only strsplit

strsplit(one, "_(?=[^_]+$)", perl = TRUE)[[1]]
strsplit(two, "_(?=[^_]+$)", perl = TRUE)[[1]]
#[1] "N,N-DIMETHYLFORMAMIDE" "kidney"      

data

two <- "N,N-DIMETHYLFORMAMIDE_kidney"