I need to make a conditional that is true if a particular matching text is found at least once in a string of text, e.g.:
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
How can I check if the text is found somewhere in the string?
There are 2 options to find matching text;
string.matchorstring.find.Both of these perform a Lua patten search on the string to find matches.
string.find()Returns the
startIndex&endIndexof the substring found.The
plainflag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than(tiger)being interpreted as a pattern capture group matching fortiger, it instead looks for(tiger)within a string.Going the other way, if you want to pattern match but still want literal special characters (such as
.()[]+-etc.), you can escape them with a percentage;%(tiger%).You will likely use this in combination with
string.subExample
string.match()Returns the capture groups found.
Example