Basic String Patterns
Basic String Patterns
A string pattern is a combination of characters that can be used to find very specific pieces (often called substrings) that exist inside a longer string.
In your games, you might use a string pattern to find every letter A inside a word, or look for a number inside a sentence.
Simple matches can be done with the Lua
Lua Libraries/string|string.match() function. This example looks for the word Roblox within two strings:
As you can see, it finds a match in the first string, so it outputs
Roblox to the console. However, it does not find a match in the second string and outputs
Simple matching is very limited and can only go so far. Consider these three statements:
Imagine you want to pull out only the number of “power gems” that exist in each world (25, 10, or 50). Because the number of gems inside each world is different, you can’t use simple matching. Instead, you need to search each statement using a character class.
In simple terms, a character class is a way to search for something that isn’t specific, but it fits within a known category (class). In Lua, you can search a string for letters, digits (numbers), spaces, punctuation, and more.
The following table shows some common and useful character classes:
||An uppercase or lowercase letter||
||A lowercase letter||
||An uppercase letter||
||Any digit (number)||
||Any punctuation character||
||An alphanumeric character (either a letter or a number)||
||A space or whitespace character||
Using a Character Class
The table above might look overwhelming, but don’t worry, we’ll go through some basic examples and show you how it works.
Let’s start with the first statement:
In the table, notice that the
%d character class lets you look inside a string for a digit (number). That’s perfect for finding out how many “power gems” exist in each of the imaginary game worlds! Let’s test out a bit of code:
Notice that the output for this code is
2 — but wait, the Cloud Kingdom has 25 power gems, not just 2! So what went wrong?
An important detail about character classes is that, by themselves, they only match one character in a string. The pattern above (
%d) starts reading the string from left to right, looks for the first digit it finds (
2), and stops!
Fortunately, you can expand the power of character classes with quantifiers.
A quantifier is a symbol typed after a character class. It lets you match a specific amount of characters defined by the class.
||Match 1 or more of the preceding character class|
||Match as few of the preceding character class as possible|
||Match 0 or more of the preceding character class|
||Match 1 or less of the preceding character class|
Let’s use a quantifier to find the correct number of power gems in the Cloud Kingdom:
As you can see, this pattern search finds the first digit (
2) but now continues on to find
5 as well! Even better, it would continue finding more numbers if they existed, for example: