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

Finding text with find and match

find locates a pattern and match pulls out the piece you asked for.

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

lua
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
Common Mistakes
  1. Assuming Lua patterns are full regular expressions
  2. Using a backslash instead of a percent sign to escape
  3. 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

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.