You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何转换str_locate_all输出为包含模式匹配所有位置的列表

转换str_locate_all输出为全量匹配索引

你可以通过遍历str_locate_all()返回的列表结果,对每组匹配的起止位置生成连续整数序列,再拼接得到目标格式。

实现代码

首先加载依赖包,我们先构造和你示例完全一致的输入结构做测试:

library(stringr)
# 模拟你的输入结构
match_loc <- list(
  matrix(c(4, 7), ncol = 2, dimnames = list(NULL, c("start", "end"))),
  matrix(c(8, 12, 30, 33), ncol = 2, byrow = TRUE, dimnames = list(NULL, c("start", "end")))
)

基础R版本转换逻辑,不需要额外安装包:

full_index <- lapply(match_loc, function(loc_matrix) {
  all_pos <- apply(loc_matrix, 1, function(row) {
    seq(from = row["start"], to = row["end"])
  })
  as.integer(unlist(all_pos))
})

运行后输出和你预期完全一致:

> full_index
[[1]]
[1] 4 5 6 7

[[2]]
[1]  8  9 10 11 12 30 31 32 33

如果你日常使用tidyverse生态,也可以用更简洁的purrr写法:

library(purrr)
full_index <- map(match_loc, ~as.integer(unlist(pmap(., seq))))

内容的提问来源于stack exchange,提问作者eglh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 21:39:04