【问题标题】:R - Extract info after nth occurrence of a character from the right of stringR - 从字符串右侧第 n 次出现字符后提取信息
【发布时间】:2018-04-16 10:50:10
【问题描述】:

我见过多次使用gsub 提取的迭代,但它们主要处理从左到右或在一次发生后提取。我想从右到左匹配,计算出现四次 -,匹配第 3 次和第 4 次之间的所有内容。

例如:

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

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

【问题讨论】:

  • 最肮脏的解决方案:反转你的输入字符串,匹配它,然后反转匹配的模式。

标签: r regex string parsing gsub


【解决方案1】:

你可以使用

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

a demo on regex101.com


R 这可能是
library(dplyr)
library(stringr)
df <- data.frame(string = c('here-are-some-words-to-try', 'a-b-c-d-e-f-g-h-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          a-b-c-d-e-f-g-h-i       f
3            no dash in here    <NA>

【讨论】:

  • 这将是我试图去的原始方向,除了它是我需要的倒退。例如,这将抓取“here-are”而不是“some-words-to-try”。有没有办法扭转被抓住的东西?
  • @alexb523:不确定您的意思,请参阅更新后的答案,它会产生您想要的结果。
  • 谢谢,我正在尝试使用 w/gsub。这适用于您上面描述的代码。
  • @alexb523:很高兴为您提供帮助。
【解决方案2】:
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" 

【讨论】:

  • 破折号太少的输入错误。可能应该给 NA 代替,但这可能留给 OP/用户,我猜。
【解决方案3】:

拆分你的句子怎么样?类似的东西

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]))

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多