How do I return multiple string matches if I don't know how many matches there are?

I want to get multiple specific phrases from this message: "Hey, [/variable=PlayerName]! How are [/variable=Friend1] and [/variable=Friend2]?"

I know that I can say

local Match1,Match2,Match3 = string.match(message, "%[/variable=(%w+)%]")

to assign to matches to variables because I know that there are three matches, but let’s say I don’t know how many matches there are. I can’t do

local Matches = string.match(message, "%[/variable=(%w+)%]")

because it only returns one match.

What can I do to get all matches there are in a string?

You can pack them into a table.

local Matches = { string.match(message, "%[/variable=(%w)%]") }

Since string.match only returns the match or its captures, you’d need to use string.gmatch in a loop.

local matches = {}

for m in string.gmatch(message, "%[/variable=(%w+)%]") do
    table.insert(matches, m)
end
-- do whatever with `matches`
4 Likes

This only returns one match.

local Matches = { string.match("Hey, [/variable=PlayerName]! How are [/variable=Friend1] and [/variable=Friend2]?", "%[/variable=(%w+)%]") };

print(Matches[1]); --> "PlayerName"
print(Matches[2]); --> nil

This is exactly what I needed!

for match in string.gmatch(e, "%[/variable=(%w+)%]") do 
    print(match) --> "PlayerName", "Friend1", "Friend2"
end

Thanks!