You can also create your own classes by wrapping a group of characters in square brackets. See the patterns manual (linked at the top of the tutorial) for a list of all pre-defined classes. Making the letter after the % uppercase inverts the class, so %D will match all non-digit characters. > = string.match( "text with an Uppercase letter", '%u') - %u matches an uppercase letter > = string.match( "foo 123 bar", '%d%d%d') - %d matches a digit Patterns have a few pre-defined classes, use them as "%x", where "x" is the letter identifying the class: It returns the matched text, or nil if the pattern is not found: (actually, find also returns the matched text, but it first returns the indexes match only returns the text) We can now use these indices to get the matched text, but there's a better way: the string.match function. is a character class that matches any character: A character class is a pattern that matches one of a set of characters. > = string.find( 'banana', 'lua') - 'lua' will not be found nilīut literally matching text isn't that useful, so patterns have the concept of character classes. > = string.find( 'banana', 'an') - find 1st occurance of 'an' (letters are matched literally) If you're used to other languages that have regular expressions to match text, remember that Lua's pattern matching is not the same: it's more limited, and has different syntax.Īfter reading this tutorial, it's very strongly recommended to read the manual on patterns, so you know everything it offers.įirst we will use the string.find function, which finds the first occurrence of a pattern in a string and returns start and end indices of the first and last characters that matched the text: Lua patterns can match sequences of characters, where each character can be optional, or repeat multiple times. Lua-users wiki: Patterns Tutorial Patterns Tutorial
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |