string.gmatch()

The string.gmatch() function provides an iterator to search for substrings in a string that match a given pattern. It is commonly used in loops for pattern-based string processing.

Syntax

string.gmatch(s, pattern)

Parameters

  • Name
    s
    Type
    string
    Description

    The string to search for substrings.

  • Name
    pattern
    Type
    string
    Description

    The Lua pattern to match substrings. Patterns can include literal characters, character classes, and special characters.

Return Value

Returns an iterator function that, when called repeatedly, produces substrings matching the specified pattern until no more matches are found.

Examples

Example 1: Extract Words from a Sentence

Use string.gmatch() to iterate through words in a string.

Example 1

local text = "Lua is a powerful, fast, and lightweight scripting language."

for word in string.gmatch(text, "%a+") do
  print(word)
end

-- Output:
-- Lua
-- is
-- a
-- powerful
-- fast
-- and
-- lightweight
-- scripting
-- language

Example 2: Extract Numbers from a String

Match numeric values within a string.

Example 2

local data = "2023-01-27"

for number in string.gmatch(data, "%d+") do
  print(number)
end

-- Output:
-- 2023
-- 01
-- 27

Example 3: Find Key-Value Pairs

Extract key-value pairs from a formatted string.

Example 3

local query = "name=John&age=30&city=London"

for key, value in string.gmatch(query, "(%w+)=(%w+)") do
  print(key, value)
end

-- Output:
-- name John
-- age 30
-- city London

Example 4: Iterate Over Delimited Substrings

Split a string by commas.

Example 4

local csv = "apple,banana,cherry,dates"

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

-- Output:
-- apple
-- banana
-- cherry
-- dates

Use Cases

  • Text Parsing: Extract words, numbers, or custom patterns from strings.
  • CSV Handling: Split data by delimiters like commas or semicolons.
  • Key-Value Matching: Parse query strings or configuration settings.
  • Pattern Matching: Search and extract substrings based on Lua patterns.

See also

  • string.match(): Finds the first occurrence of a pattern in a string, useful for single matches instead of iteration.
  • string.gsub(): Replaces occurrences of a pattern, complementary for processing strings after matching.
  • string.sub(): Extracts specific parts of a string, useful when combined with string.gmatch() for targeted manipulation.

Was this page helpful?

Table of Contents