Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What do quantifiers do (string patterns)?

I read the wiki about *, +, - and ? but its all flying right over my head. Can someone explain what they mean and do?

1 answer

✓ Accepted answer

Quantifiers simply modify the behavior of the previous specifier in the string pattern.

For example, let's say we want to match a number in a string. We can use the %d character class:

local OurString = "3"
print(OurString:match("%d")) --> 3

What happens when we make OurString a multi-digit number, such as 5000?

local OurString = "5000"
print(OurString:match("%d")) --> 5

The string pattern match only found the first digit, because that's all we told it to look for.

Instead, we need to use a quantifier. We want to match one or more digits, so we'll use the + quantifier like so:

local OurString = "5000"
print(OurString:match("%d+")) --> 5000

Since the + quantifier matches one or more of the previous specifier, and our previous specifier is the %d character class (which again, matches a digit), we are attempting to match a sequence of one or more digits in the string.

The * quantifier matches zero or more of the preceding character specifier. In practice, this means that the specifier is optional, and can be of any length.

Let's try to match the letter "a", followed by zero or any number of digits, followed by "b":

local OurString = "cab"
local AnotherString = "ca1234138328989328392be"
local OtherString = "a0b5"

local Pattern = "a%d*b"

print(OurString:match(Pattern)) --> "ab"
print(AnotherString:match(Pattern)) --> "a1234138328989328392b"
print(OtherString:match(Pattern)) --> "a0b"

As we can see, the digits between the "a" and the "b" in our strings when matched are completely optional.

There are two other quantifiers too, namely the ? quantifier, which matches zero or one repititions of the preceding specifier, and the - quantifier, which tries to match as few repititions of the preceding specifier as possible.

Quantifiers are all about modifying the behavior of the last character specifier, and trying to match repeated occurences specifiers.

This discussion is preserved as it was. New answers, comments, and votes are closed.