Reputation: 57
What is a way that I can find (and loop through) all instances of a string within another string in lua? For example, if I have the string
"honewaidoneaeifjoneaowieone"
And I want to loop through all instances (and by this, I mean indexes) of "one" within that string, well, I can see that it appears four times, but I have no clue how to actually find them. I know that string.find() can find the first instance, but that doesn't help me very much.
Upvotes: 3
Views: 2327
Reputation: 72422
You can tell string.find
where to start the search:
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
This code starts each search after the end of the previous match, that is, it finds only non-overlapping occurrences of a string. If you want to find overlapping occurrences of a string, use b=x+1
instead.
Upvotes: 3
Reputation: 7064
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)
Upvotes: 2