0Pricing
Lua Academy · Lesson

Finding and Extracting Substrings

Apply string.find and string.sub to locate and extract text.

string.find Basics

string.find(s, pattern, init, plain) searches for a pattern in s starting at init (default 1). It returns the start and end positions of the match, or nil if not found. With plain=true, it treats the pattern as a literal string (no magic characters).

local s = "hello world"
local i, j = string.find(s, "world")
print(i, j)    -- 7  11

-- Plain search (literal string)
local i2, j2 = string.find("a+b=5", "+", 1, true)
print(i2, j2)  -- 2  2

-- Not found
print(string.find(s, "xyz"))  -- nil

string.sub for Extraction

string.sub(s, i, j) extracts the substring from position i to j (inclusive). Negative indices count from the end: -1 is the last character. If j is omitted, it defaults to the end of the string.

local s = "hello world"
print(string.sub(s, 1, 5))    -- hello
print(string.sub(s, 7))       -- world
print(string.sub(s, -5))      -- world
print(string.sub(s, 1, -7))   -- hello
print(s:sub(7, 11))           -- world (method syntax)

All lessons in this course

  1. String Basics: Concat and Length
  2. Finding and Extracting Substrings
  3. string.format for Output
  4. string.gsub and string.gmatch
← Back to Lua Academy