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