util.string.gmatch

Shared

Returns an iterator function for pattern matching


Syntax

local iterator = util.string.gmatch(
    input,
    pattern
)

Parameters

TypeNameDescription
stringinputString to iterate over
stringpatternLua pattern to match repeatedly

Returns

TypeNameDescription
functioniteratorIterator function that returns the next match (or captures) each time it's called

Examples

Iterate over all words in a string
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'
]]
Extract all numbers from a string
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'
]]
Extract key-value pairs
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'
]]
Split a string by delimiter
local csv = "apple,banana,orange"

for item in util.string.gmatch(csv, "[^,]+") do
    core.engine.print("info", item)
end

--[[
Output: 
'apple'
'banana'
'orange'
]]
Collect all matches into a table
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'
Match quoted strings
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'
]]
Extract email addresses
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'
]]
Count pattern matches
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

On this page