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

如何让str_locate_all函数识别字符串中的所有重叠匹配模式?

让stringr的str_locate_all返回重叠匹配结果

在使用stringr包的str_locate_all函数查找字符串中的连续模式时,默认只会返回非重叠的匹配结果:

library(stringr)
string = paste0(c(5,5,5,6,6,5,5,6), collapse = "")
pattern = paste0(c(5,5), collapse = "")

str_locate_all(string, pattern)
[[1]]
     start end
[1,]     1   2
[2,]     6   7

比如在字符串'55566556'中查找'55',位置2-3的重叠匹配会被忽略,若想得到包含所有重叠结果的输出:

> str_locate_all(string, pattern)
[[1]]
     start end
[1,]     1   2
[2,]     2   3
[3,]     6   7

可以通过正向零宽预查修改正则模式来实现:

library(stringr)
string = "55566556"
# 用正向预查匹配所有"55"的起始位置
match_positions <- str_locate_all(string, "(?=55)")[[1]]
# 计算对应结束位置(原模式长度为2,end = start + 1)
match_positions[, "end"] <- match_positions[, "start"] + 1
match_positions

运行后会输出预期的结果:

start end
[1,]     1   2
[2,]     2   3
[3,]     6   7

原理说明

正向预查(?=55)属于零宽度断言,它不会消耗字符串中的字符,仅检查当前位置后方是否存在"55"。匹配后指针不会移动,因此能捕捉到所有重叠的起始位置,再通过计算得到对应的结束位置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:50:22