Lua Pattern Captures
A capture is a part of a pattern marked by parentheses that string.find and string.match return separately. Parentheses do not change what the pattern matches, only which parts come back on their own.
Parentheses mark the parts that come back
string.find returns the start and end positions, then each capture.
local s, e, first, second = string.find("red blue", "(red) (blue)")
print(s, e, first, second)string.match returns captures without positions
The same pattern gives only the captured words.
local first, second = string.match("red blue", "(red) (blue)")
print(first, second)Without parentheses there is no separate part
A pattern with no parentheses returns the whole match as one value.
local whole = string.match("red blue", "red blue")
print(whole)Example
local one, two, three = string.match("spring summer autumn", "(spring) (summer) (autumn)")
print(one, two, three)
print(three, two, one)Key points
- Capture: parentheses around part of a pattern mark that part for return.
- Use string.find with a pattern to get the start position, the end position, and then each capture in order.
- Use string.match to get the captures on their own, with no positions.
- Order: captures come back in the order their opening parentheses appear.
- Without parentheses, find returns only positions and match returns only the whole match.
In this example, the pattern has three captures, one for each season. The first print shows them in opening order, and the second print shows them in reverse order, which proves each capture is a separate value that can be used on its own.
Note
a capture returns the exact text that matched, not the pattern itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does string.match("red blue", "(red) (blue)") return?