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?
sjr04
(uep)
April 13, 2020, 3:27pm
#2
You can pack them into a table.
local Matches = { string.match(message, "%[/variable=(%w)%]") }
Autterfly
(Autterfly)
April 13, 2020, 3:31pm
#3
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!