根据索引查找字符串

时间:2019-11-09 17:56:01

标签: r regex

我正在尝试查找已知字符串之后的字符串: string_n = 1 .... 因此,我尝试确定索引“ n =”,然后找出它的实验次数(在本例中为1)。我该怎么做? 到目前为止,这是我的方法,但无法正常工作,我无法获得exp_number的值:

library(stringr)

for (i in length(names)){

  pos_of_n = str_which(pattern = '=', names[i], fixed = TRUE)

  substring = names[I]

  exp_number = substring[pos_of_n[1]+1]

  exp_name <- paste("exp", toString(exp_number,width=NULL))

}

1 个答案:

答案 0 :(得分:1)

我假设您的数据看起来像下面的字符串。

library(stringr)
strings <- c('exp n=1', 'exp n=2 more information...')

# Returns a matrix. First column is complete match, second the first
# set of parentheses, third the second set of parentheses -- which is
# the one we want.
exp_numbers <- str_match(strings, '(n\\=)(\\d+)')[,3]
# [1] "1" "2"
paste0("Exp", exp_numbers)
# [1] "Exp1" "Exp2"

# Using the data string you provided
strings <- c(' D:Maj_stats_n1_pooled2019-0918_screen_n=3_T_Template.csv')
exp_numbers <- stringr::str_match(strings, '(n\\=)(\\d+)')[,3]
labels <- paste0("Exp", exp_numbers)
labels
#> [1] "Exp3"
相关问题