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

如何在单个字符串中查找匹配项位置(而非字符向量)

在单个字符串中查找所有模式匹配的位置

以下两个现成的高效函数可以满足你的需求,均经过底层优化,适合数千次重复运行:

1. Base R 内置函数 gregexpr()

无需额外安装包,直接使用内置函数即可获取所有匹配的起始位置,支持单字符和多字符模式:

t <- 'killer'
p <- 'l'

# 获取匹配位置向量
match_positions <- gregexpr(p, t)[[1]]
# 处理无匹配的情况(返回空向量)
if (all(match_positions != -1)) match_positions else integer(0)
# 输出结果:3 4

多字符模式示例:

gregexpr('ill', t)[[1]]
# 输出结果:2(对应字符串中"ill"的起始位置)

2. stringr 包的 str_locate_all()

如果需要同时获取匹配的起始和结束位置,stringr 的这个函数更直观,返回结构清晰的矩阵:

library(stringr)

t <- 'killer'
p <- 'l'

# 获取所有匹配的起止位置矩阵
match_matrix <- str_locate_all(t, p)[[1]]
# 提取起始位置
start_pos <- match_matrix[, "start"]
# 输出结果:3 4

# 多字符模式示例
str_locate_all(t, 'ill')[[1]]
# 输出结果:
#      start end
# [1,]     2   4

这两个函数均为底层优化实现,性能远优于自定义函数,完全适配你的批量运行需求。

内容的提问来源于stack exchange,提问作者Théodore Targerian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:21:02