在一个字符串中查找所有出现的子字符串

3
什么方法可以在lua中查找(并循环遍历)一个字符串中所有的子字符串?例如,如果我有一个字符串:
"honewaidoneaeifjoneaowieone"

我希望能够遍历字符串中所有"one"的实例(也就是索引),虽然我可以看到它出现了四次,但我不知道如何找到它们。我知道string.find()可以找到第一个实例,但这并没有什么帮助。


for index in ("honewaidoneaeifjoneaowieone"):gmatch("()one") do print(index) end - Egor Skriptunoff
那看起来应该可以工作。不过你能把它发布为答案吗? - Novarender
如果你在字符串aaaa中搜索子字符串aaa,我的解决方案效果不佳。让我们等待一个带有“循环内find()”解决方案的答案。 - Egor Skriptunoff
好的。对我来说这个方法有效,因为我的情况适用于它,但是括号"()one"的作用是什么? - Novarender
1
空括号表示“位置索引”。 - Egor Skriptunoff
2个回答

3

您可以告诉string.find从哪里开始搜索:

s="honewaidoneaeifjoneaowieone"
p="one"
b=1
while true do
    local x,y=string.find(s,p,b,true)
    if x==nil then break end
    print(x)
    b=y+1
end

这段代码在上一个匹配结束后开始每次搜索,也就是说,它只会找到字符串的非重叠出现。如果你想要查找字符串的重叠出现,请使用 b=x+1


2
local str = "honewaidoneaeifjoneaowieone"

-- This one only gives you the substring;
-- it doesn't tell you where it starts or ends
for substring in str:gmatch 'one' do
   print(substring)
end

-- This loop tells you where the substrings
-- start and end. You can use these values in
-- string.find to get the matched string.
local first, last = 0
while true do
   first, last = str:find("one", first+1)
   if not first then break end
   print(str:sub(first, last), first, last)
end

-- Same as above, but as a recursive function
-- that takes a callback and calls it on the
-- result so it can be reused more easily
local function find(str, substr, callback, init)
   init = init or 1
   local first, last = str:find(substr, init)
   if first then
       callback(str, first, last)
       return find(str, substr, callback, last+1)
   end
end

find(str, 'one', print)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接