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

如何在Lua中获取文本中所有匹配关键词的起始索引?

Lua 获取文本中所有匹配关键词的起始索引

你可以通过循环调用string.find()并更新查找起始位置的方式,获取所有匹配的起始索引。string.find()的第三个参数可以指定从字符串的哪个位置开始查找,每次找到匹配后,将起始位置设置为上次匹配的结束位置+1,就能继续查找下一个结果,直到找不到为止。

示例代码:

local Word = "yes"
local String = "yes, i said yes"

local start_pos = 1
while true do
    -- 从start_pos位置开始查找Word
    local match_start, match_end = string.find(String, Word, start_pos)
    -- 找不到匹配就退出循环
    if not match_start then break end
    -- 输出起始索引
    print(match_start)
    -- 更新起始位置,避免重复匹配当前结果
    start_pos = match_end + 1
end

运行这段代码会输出:

1
13

如果需要支持重叠匹配(比如在字符串"aaaaa"中查找"aa",希望得到1、2、3、4这些起始索引),只需要把start_pos = match_end + 1改成start_pos = match_start + 1即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:52:02