Menu
Coddy logo textTech

Iterating with string.gmatch()

Part of the Logic & Flow section of Coddy's Lua journey — lesson 39 of 54.

While string.match() finds the first occurrence of a pattern, what if you need to find all matches in a string? The string.gmatch() function solves this by returning an iterator that you can use in a for loop to process each match one by one.

The basic syntax looks like this:

for match in string.gmatch(text, pattern) do
    -- process each match
end

Here's an example that finds all numbers in a string:

local text = "I have 3 apples and 5 oranges"
for number in string.gmatch(text, "%d+") do
    print(number)
end
-- Output:
-- 3
-- 5

The pattern %d+ matches one or more digits, and the loop runs once for each number found.

You can also extract all words from a sentence:

local sentence = "Lua is a powerful language"
for word in string.gmatch(sentence, "%a+") do
    print(word)
end
-- Output:
-- Lua
-- is
-- a
-- powerful
-- language
challenge icon

Challenge

Easy

Write a function extractHashtags that takes text and returns all hashtags found in the text, each on a separate line.

Use string.gmatch() to find all hashtags in the text. A hashtag starts with # followed by one or more letters.

Logic:

  • Use string.gmatch() with the pattern "#%a+" to find all hashtags
  • Iterate through each match and collect them
  • Join all hashtags with newline characters (\n)
  • If no hashtags are found, return an empty string

Parameters:

  • text (string): The text to search for hashtags

Returns: All hashtags found, each on a separate line. If no hashtags exist, return an empty string (string)

Cheat sheet

The string.gmatch() function returns an iterator that finds all occurrences of a pattern in a string, allowing you to process each match in a for loop.

Basic syntax:

for match in string.gmatch(text, pattern) do
    -- process each match
end

Example finding all numbers:

local text = "I have 3 apples and 5 oranges"
for number in string.gmatch(text, "%d+") do
    print(number)
end
-- Output:
-- 3
-- 5

Example extracting all words:

local sentence = "Lua is a powerful language"
for word in string.gmatch(sentence, "%a+") do
    print(word)
end
-- Output:
-- Lua
-- is
-- a
-- powerful
-- language

Try it yourself

function extractHashtags(text)
    -- Write code here
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow