最后一个特殊字符的gsub

时间:2017-12-22 15:41:08

标签: r regex split gsub

我想得到两个字符串,它们出现在最后一个特殊字符(即_)之前和之后。

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

我期待结果

string1 = TRANS-PLATINUM_(II)_DIAMMINE_DICHLORIDE

string2 = kidney

1 个答案:

答案 0 :(得分:2)

我们可以使用

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

或仅使用strsplit

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

数据

two <- "N,N-DIMETHYLFORMAMIDE_kidney"