从 str_locate_all 中的多个位置提取 'end' 个位置?

Extract 'end' locations from multiple locations in str_locate_all in R?

如果我们像这样在字符串向量中找到一个子字符串

library(stringr)
library(dplyr)

x <- c("ldksfABCskdlfj",
       "kABCz",
       "skdlfjlsjfABCksdfpjfkj")

x %>% str_locate_all("ABC")

我们得到

[[1]]
     start end
[1,]     6   8

[[2]]
     start end
[1,]     2   4

[[3]]
     start end
[1,]    11  13

如何提取结束个位置? (即 8、4、13)

到目前为止我尝试了什么

x %>% str_locate_all("ABC") %>% sapply(function(x) { .[1,2] })
# Error in .[1, 2] : incorrect number of dimensions

快到了。这是一种方法:

x %>% str_locate_all("ABC") %>% sapply(., function(x) x[,2])

如果您在每个字符串中只有一个匹配项,如示例所示,您可以使用 str_locate 代替,这将避免使用任何循环来提取 "end" 列,因为您可以直接从中提取子集矩阵返回。

stringr::str_locate(x, "ABC")[, 2]
#[1]  8  4 13

我们可以使用

library(stringr)
library(dplyr)
str_locate(x, "ABC") %>% 
        as_tibble %>% 
        pull(end)
 #[1]  8  4 13