Lua - String find() method
string.find() is one of the primary method of Lua built-in library for pattern matching.
Syntax
start, finish = string.find(s, pattern [, init [, plain]])
Where −
s − is the string to be searched in.
pattern − pattern to match
init − Optional. Index to start the search. Default: 1
plain − Optional. Boolean value. If true, pattern matching is turned off, and pattern is treated as plain text. Default: false.
Returns
start and end index of the first match found. If no match found, nil is returned.
Example - Usage of String.find() function
main.lua
local text = "Welcome to Lua!"
local pattern = "Lua"
-- search the pattern in text
local start, finish = string.find(text, pattern)
-- if start is not nil
if start then
print("Pattern found at:", start, "to", finish) -- Prints Pattern found at: 12 to 14
end
pattern = "Programming"
-- search the non-matching pattern in text
local start, finish = string.find(text, pattern)
-- if start is nil
if not start then
print("Pattern not found.") -- Prints Pattern not found.
end
Output
When we run the above program, we will get the following output−
Pattern found at: 12 to 14 Pattern not found.
Example - Using Special Characters with string.find()
main.lua
local text = "Hello 1234."
-- Search any sequence of digits
local start, finish = string.find(text, "%d+")
print("Digit sequence:", string.sub(text, start, finish)) -- prints Digit sequence: 1234
-- Search a pattern in the beginning of the string
local start, finish = string.find(text, "^Hello")
if start then
print("Sentence starts with 'Hello'") -- prints Sentence starts with 'Hello'
end
-- Search a pattern at the end of the string
local start, finish = string.find(text, "%d+%$")
if not start then
print("Sentence does not end with digits.") -- prints Sentence does not end with digits.
end
Output
When we run the above program, we will get the following output−
Digit sequence: 1234 Sentence starts with 'Hello' Sentence does not end with digits.
Advertisements