Lua - String gmatch() method



string.gmatch() is a very useful string libraray function for pattern matching for multiple occurences of a string. string.gmatch() returns an iterator function. Everytime, we calls string.gmatch() function, it returns the next captured string based on the pattern provided.

Syntax

string.gmatch(s, pattern)

Where −

  • s − is the string to be searched in.

  • pattern − pattern to match. We can use specialized characters, quantifiers and capture groups in the pattern.

Returns

an iterator over the captures

Working of string.gmatch() function

  • string.gmatch() returns an iterator.

  • Every time, the iterator is called, it returns the next set of captured value using the pattern on the string.

  • If there is no captured string(using parenthesis), the entire matched word is returned.

Example - Usage of String.gmatch() function

In this example, we're printing words of a line.

main.lua

local data = "apple, banana, mango"

-- Iterate over all words and print each word on separate line
for word in string.gmatch(data, "%w+") do
  print(word)
end

Output

When we run the above program, we will get the following output−

apple
banana
mango

Example - Handing paired values

main.lua

local data = "name=Alice,age=30,city=NewYork"

-- Iterate over comma-separated value pairs
for key, value in string.gmatch(data, "(%w+)=(%w+)") do
  print("Key:", key, "Value:", value)
end

Output

When we run the above program, we will get the following output−

Key:    name    Value:  Alice
Key:    age     Value:  30
Key:    city    Value:  NewYork
Advertisements