String
string.gmatch
Shared
Returns an iterator function for pattern matching
Syntax
local iterator = string.gmatch(input, pattern)Parameters
| Type | Name | Description |
|---|---|---|
string | input | String to be iterated over |
string | pattern | Lua pattern to match repeatedly |
Returns
| Type | Name | Description |
|---|---|---|
function | iterator | Iterator function that returns the next match (or captures) each time it's called |
Examples
local text = "hello world from Lua"
for word in string.gmatch(text, "%a+") do
engine.print("info", word)
end
--[[
Output:
'hello'
'world'
'from'
'Lua'
]]local data = "x=10, y=20, z=30"
for num in string.gmatch(data, "%d+") do
engine.print("info", num)
end
--[[
Output:
'10'
'20'
'30'
]]local coords = "x=5 y=10 x=15 y=20"
for key, value in string.gmatch(coords, "(%a+)=(%d+)") do
engine.print("info", key, value)
end
--[[
Output:
'x 5'
'y 10'
'x 15'
'y 20'
]]local csv = "apple,banana,orange"
for item in string.gmatch(csv, "[^,]+") do
engine.print("info", item)
end
--[[
Output:
'apple'
'banana'
'orange'
]]local words = {}
for word in string.gmatch("one two three", "%S+") do
table.insert(words, word)
end
engine.print("info", table.concat(words, " | ")) --'one | two | three'local text = 'name="John" age="25" city="NYC"'
for value in string.gmatch(text, '"(.-)"') do
engine.print("info", value)
end
--[[
Output:
'John'
'25'
'NYC'
]]local text = "Contact: john@example.com or jane@example.com"
for email in string.gmatch(text, "%S+@%S+") do
engine.print("info", email)
end
--[[
Output:
'john@example.com'
'jane@example.com'
]]local count = 0
for _ in string.gmatch("the cat sat on the mat", "the") do
count = count + 1
end
engine.print("info", count) --2