Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if matching text is found in a string in Lua?

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?

like image 945
Village Avatar asked Apr 15 '12 00:04

Village


People also ask

How do I match a string in Lua?

> = string. match("foo 123 bar", '%d%d%d') -- %d matches a digit 123 > = string. match("text with an Uppercase letter", '%u') -- %u matches an uppercase letter U. Making the letter after the % uppercase inverts the class, so %D will match all non-digit characters.

What does GSUB do in Lua?

gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern.

What is a string value in Lua?

A StringValue is an object whose purpose is to store a single Lua string. The length of the string can't be more than 200,000 characters (this will cause a “String too long” error). Like all “-Value” objects, this single value is stored in the Value property.


1 Answers

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag) 

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex 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.sub

Example

str = "This is some text containing the word tiger." if string.find(str, "tiger") then   print ("The word tiger was found.") else   print ("The word tiger was not found.") end 

string.match()

string.match(s, pattern, optional index) 

Returns the capture groups found.

Example

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.") end 
like image 93
hjpotter92 Avatar answered Sep 23 '22 19:09

hjpotter92