Skip to content
Lua

String Manipulation

Pattern matching and string functions in Lua.

By EZ4Code Team
stringpatternmatch

Code

local s = "Hello, World!"

-- Basic functions
print(#s)                      -- 13 (length)
print(string.upper(s))         -- "HELLO, WORLD!"
print(string.lower(s))         -- "hello, world!"
print(string.sub(s, 1, 5))     -- "Hello"
print(string.rep("-", 10))     -- "----------"

-- Find and replace (Lua patterns, NOT regex!)
local date = "2024-06-15"
local y, m, d = date:match("(%d+)-(%d+)-(%d+)")
print(y, m, d)  -- 2024 06 15

-- gsub: replace all
local new = ("hello world"):gsub("o", "0")  -- "hell0 w0rld"
print(new)

-- Format
print(string.format("Pi: %.2f", 3.14159))  -- "Pi: 3.14"
print(string.format("%5d", 42))             -- "   42"

-- Split (not built-in, implement with gmatch)
local function split(str, sep)
  local parts = {}
  for part in str:gmatch("([^" .. sep .. "]+)") do
    table.insert(parts, part)
  end
  return parts
end
print(split("a,b,c", ","))  -- {a, b, c}

Explanation

Lua patterns are simpler than regex — %d for digits, %a for letters, %w for alphanumeric, + for one-or-more. capture with (…) and match returns captures. gsub replaces (returns string + count). Lua has no built-in split — use gmatch. The : syntax (s:upper()) is sugar for string.upper(s).

More Lua Snippets