繁体   English   中英

R - 从字符串右侧第n次出现字符后提取信息

[英]R - Extract info after nth occurrence of a character from the right of string

我已经看过许多提取w / gsub迭代,但它们主要处理从左到右或一次出现之后的提取。 我想从右到左匹配,计算四次出现- ,匹配第3次和第4次出现之间的所有事情。

例如:

string                       outcome
here-are-some-words-to-try   some
a-b-c-d-e-f-g-h-i            f

以下是我尝试过的一些参考资料:

x = c("here-are-some-words-to-try", "a-b-c-d-e-f-g-h-i")
sapply(x, function(strings){
    ind = unlist(gregexpr(pattern = "-", text = strings))
    if (length(ind) < 4){NA}
    else{substr(strings, ind[length(ind) - 3] + 1, ind[length(ind) - 2] - 1)}
})
#here-are-some-words-to-try          a-b-c-d-e-f-g-h-i 
#                    "some"                        "f" 

你可以用

([^-]+)(?:-[^-]+){3}$

请参阅regex101.com上的演示


R这可能是

 library(dplyr) library(stringr) df <- data.frame(string = c('here-are-some-words-to-try', 'abcdefgh-i', ' no dash in here'), stringsAsFactors = FALSE) df <- df %>% mutate(outcome = str_match(string, '([^-]+)(?:-[^-]+){3}$')[,2]) df 

和收益率

  string outcome 1 here-are-some-words-to-try some 2 abcdefghi f 3 no dash in here <NA> 

分裂你的句子怎么样? 就像是

string <- "here-are-some-words-to-try"

# separate all words
val <- strsplit(string, "-")[[1]]

# reverse the order
val rev(val)

# take the 4th element
val[4]

# And using a dataframe
library(tidyverse)
tibble(string = c("here-are-some-words-to-try", "a-b-c-d-e-f-g-h-i")) %>% 
mutate(outcome = map_chr(string, function(s) rev(strsplit(s, "-")[[1]])[4]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM