find, match, gsub and Patterns

Often you need to search inside text. Does this line contain a number? Where is it? Can you replace it? Lua has three functions for this: find, match and gsub.

find: where is it?

local order = "table for 4 at 19:30"
print(order:find("for"))
print(order:find("pizza"))

Output:

7	9
nil

find returns two values: the position where the match starts, and the position where it ends. for is at characters 7 to 9. When there is no match, find returns nil. Because nil counts as false, if text:find("for") then is a simple way to ask "does the text contain this?".

match and patterns

The text you search for is a pattern. Most characters in a pattern match themselves, but a few have a special meaning. %d means "any digit", and + means "one or more of the thing before it". So %d+ means "one or more digits in a row".

local order = "table for 4 at 19:30"
print(order:match("%d+"))
print(order:match("%d+:%d+"))

Output:

4
19:30

match returns the text that matched. The first pattern found 4, the first group of digits. The second pattern means "digits, a colon, digits", so it found the time.

Here are the pattern items you will use most:

PatternMatches
%da digit
%aa letter
%sa space (or a tab or newline)
.any one character
+one or more of the item before it

If you know regular expressions from another language, Lua patterns look similar but are simpler. One difference: the escape character is %, not \. To search for a real dot, write %..

gsub: replace

gsub(pattern, replacement) replaces every match. It returns two values: the new string and the number of replacements.

local order = "table for 4 at 19:30"
local changed, count = order:gsub("%d", "#")
print(changed)
print(count)

Output:

table for # at ##:##
5

The pattern can also be plain text:

local drink = "I like tea, tea is good"
print(drink:gsub("tea", "coffee"))

Output:

I like coffee, coffee is good	2

Like all string functions, gsub does not change the original string. It gives you a new one.

In the exercise, use gsub to replace every space in a line with a dash, and print how many spaces were replaced.