Captures and gmatch
gmatch loops over every match of a pattern in a string.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Calling gmatch without using it in a for loop
- Confusing - the lazy quantifier with a range
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: