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
--Iterate over all words
local text = "hello world from Lua"
for word in string.gmatch(text, "%a+") do
engine.print(word)
end
--Output: hello, world, from, Lua--Extract all numbers
local data = "x=10, y=20, z=30"
for num in string.gmatch(data, "%d+") do
engine.print(num)
end
--Output: 10, 20, 30--Extract pairs of values
local coords = "x=5 y=10 x=15 y=20"
for key, value in string.gmatch(coords, "(%a+)=(%d+)") do
engine.print(key, value)
end
--Output: x 5, y 10, x 15, y 20--Split string by delimiter
local csv = "apple,banana,orange"
for item in string.gmatch(csv, "[^,]+") do
engine.print(item)
end
--Output: apple, banana, orange--Collect matches into table
local words = {}
for word in string.gmatch("one two three", "%S+") do
table.insert(words, word)
end
engine.print(table.concat(words, " | ")) --one | two | three--Match quoted strings
local text = 'name="John" age="25" city="NYC"'
for value in string.gmatch(text, '"(.-)"') do
engine.print(value)
end
--Output: John, 25, NYC--Extract email addresses
local text = "Contact: john@example.com or jane@example.com"
for email in string.gmatch(text, "%S+@%S+") do
engine.print(email)
end
--Output: john@example.com, jane@example.com--Count matches
local count = 0
for _ in string.gmatch("the cat sat on the mat", "the") do
count = count + 1
end
engine.print(count) --2