← Back to Lua Course | Chapter 3: Strings | Lesson 5 of 7

Captures and gmatch

gmatch loops over every match of a pattern in a string.

In this page:

  1. Captures and gmatch

Captures and gmatch

string.gmatch returns an iterator that yields each match, or each set of captures, in turn. Parentheses in a pattern define captures, and the quantifiers are * + - and ?. Common uses are splitting a string into words or reading key=value pairs.

Note: The pattern [^,]+ matches any run of characters that are not commas, which is handy for splitting.

Example: Captures and gmatch

lua
for word in ("one two  three"):gmatch("%a+") do
  print(word)
end
for k, v in ("a=1, b=2"):gmatch("(%w+)=(%w+)") do
  print(k, v)
end
local fields = {}
for f in ("x,y,,z"):gmatch("[^,]+") do fields[#fields + 1] = f end
print(#fields, table.concat(fields, "|"))

-- Output:
-- one
-- two
-- three
-- a	1
-- b	2
-- 3	x|y|z
Common Mistakes
  1. Calling gmatch without using it in a for loop
  2. Confusing - the lazy quantifier with a range
  3. Forgetting the parentheses when you want captures
Chapter Summary
  • gmatch gives an iterator over matches
  • Parentheses create captures
  • * + - ? are quantifiers
  • [^x]+ matches a run without x

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.