Finding text with find and match
find locates a pattern and match pulls out the piece you asked for.
In this page:
Finding text with find and match
string.find(s, pattern, init, plain) returns the start and end positions of the first match, or nil. With the plain argument set to true it searches for literal text instead of a pattern. string.match returns the matched text, or the captures if the pattern has parentheses. Lua patterns are simpler than regular expressions and use %d for digits, %a for letters and %s for whitespace.
Note:
Special characters such as . and % in a pattern must be escaped with a percent sign.
Example: Finding text with find and match
local s = "order 66 shipped"
print(s:find("66"))
print(s:find("(%d+)"))
print(s:match("%d+"))
print(s:match("(%a+) (%d+)"))
print(("a.b"):find(".", 1, true))
print(s:find("xyz"))
-- Output:
-- 7 8
-- 7 8 66
-- 66
-- order 66
-- 2 2
-- nil
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming Lua patterns are full regular expressions
- Using a backslash instead of a percent sign to escape
- Forgetting that find returns positions, not the text
Chapter Summary
- find returns start and end indexes
- match returns the matched text or captures
- %d %a %s are character classes
- Pass true to find for a plain search
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: