Lua String Search
Lua string search tools find where a word sits in text and replace words with new ones. This lesson uses string.find and string.gsub.
Find a word's positions
string.find returns two numbers for a found word. The numbers are the positions of its first and last characters.
print(string.find("the cat sat", "cat"))A missing word gives nil
The search still runs when the word is absent. The result is nil instead of two positions.
print(string.find("the cat sat", "dog"))Replace words with string.gsub
string.gsub returns the changed string and the number of replacements. Printing the call shows both values with a tab between them.
print(string.gsub("cat cat", "cat", "dog"))Example
local text = "Please fix this mess"
print(string.find(text, "fix"))
print(string.gsub(text, "mess", "text"))Key points
- string.find: a tool that searches a string for a word and returns its start and end positions.
- Position: the number of a character counted from the start of the string, beginning at 1.
- Missing word: string.find returns nil when the word is not in the string.
- string.gsub: a tool that replaces every match of a word and returns the new string and a count.
- Replacement count: the second value from string.gsub, showing how many replacements were made.
In this example, string.find reports that fix starts at position 8 and ends at position 10. string.gsub then replaces mess with text and returns the cleaned string plus a count of 1. A later lesson shows how to keep both values returned by a function.
Note
printing a tool call with two return values shows both values separated by a tab.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does this code print? print(string.find("hello world", "world"))