🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Pattern Quantifiers

A quantifier is a symbol after a pattern piece that says how many times that piece may repeat. Quantifiers turn a single character class into a match for a whole run of characters.

Plus and star take whole runs

Plus takes one or more letters, and star takes a run that may be empty.

print(string.match("aaab", "%a+"))
print(string.match("123abc", "%d+"))
print(string.match("aab123", "%a*"))

Question takes at most one, minus takes the fewest

Question lets the u be absent, and minus stops at the first closing bracket.

print(string.match("color", "colou?r"))
print(string.match("colour", "colou?r"))
print(string.match("<a><b>", "<.+>"))
print(string.match("<a><b>", "<.->"))

Anchors pin a match and balanced pairs nest

The caret pins to the start, the dollar pins to the end, and the balanced pair keeps nested parentheses together.

print(string.match("hello world", "^%a+"))
print(string.match("hello world", "%a+$"))
print(string.match("(a (b) c)", "%b()"))
print(string.match("x (a) y", "%b()"))

Example

local text = "(one (two) three) tail"
print(string.match(text, "^%b()"))
print(string.match(text, "%a+$"))
print(string.match("aaa123", "%a+%d+"))

Key points

  • Plus: + means one or more copies of the previous piece, taking as many as possible.
  • Star: * means zero or more copies of the previous piece, taking as many as possible.
  • Question: ? means zero or one copy of the previous piece.
  • Minus: - means zero or more copies, but taking as few as possible, so it is the non-greedy form.
  • Greedy: + and * and ? take the longest match they can, while - takes the shortest.
  • Anchors: ^ at the start anchors a pattern to the start of the string, and $ at the end anchors it to the end.
  • Balanced: %b() matches a balanced pair of parentheses, from an opening parenthesis to its matching close, including nested pairs.

In this example, the anchored balanced pair takes the whole nested parentheses group from the start of the string. The anchored letter run takes tail from the end, and the last match shows a letter run followed by a digit run.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which quantifier is non-greedy, taking as few copies as possible?