Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 4: Strings and patterns

Objectives: LO-4.1, LO-4.2, LO-4.3, LO-4.4
Prerequisites: the Module 4 reading and Lab 3
Time: about 2 hours

You will predict what string functions return, parse a server log with patterns, remove notes and count words with %b and %f, turn a regular expression with alternation into Lua, measure string building with .. against table.concat, and shorten UTF-8 text without breaking a character. As in the earlier labs, each exercise ends with a check cell that prints passed or fails with a message, and the checks fail until you finish their exercise.

Setup

Nothing in this lab is random. Section 4 measures time, so its numbers depend on your machine. The second cell prints the Lua version, which should be Lua 5.4.

1. The string library

Exercise L4.1 (LO-4.1, ★, about 15 minutes)

Predict the value of each expression, and replace its "?": a string in quotes, such as "ell", or a number. Make all ten predictions before you run the check.

2. Parsing a log

The next cell stores a server’s log in the global log, as a long string. Each line has a date, a time, a level padded to five characters, a component in brackets, and a message. One line was cut short by a crash.

[^\n]+ matches a run of characters that aren’t newlines, so gmatch with it visits each line. Try a pattern of your own in the next cell before the exercise: change it to find every time of day in the log, then every component in brackets.

Exercise L4.2 (LO-4.2, ★★, about 25 minutes)

Write parse_line(line), which returns five strings for a log line: the date, the time, the level, the component without its brackets, and the message. For a line that doesn’t have that shape, it returns nil. Use one call to match with one pattern.

Hint 1

-, [, and ] are magic characters, so the pattern writes them as %-, %[, and %].

Hint 2

The level is followed by one space or two, which %s+ matches. Anchor the pattern with ^ and $, and capture the message with (.*).

Exercise L4.3 (LO-4.2, ★★, about 20 minutes)

Write two functions:

  • strip_notes(message) removes every note in parentheses, together with the spaces before it, and returns only the new string. strip_notes("slow query (users, 1532 ms)") is "slow query", and notes inside notes go with the note around them.

  • count_word(text, word) returns how many times word appears in text as a whole word, ignoring case. Assume word holds only ASCII letters. count_word("Error: error-prone errors", "error") is 2: errors is a different word.

Hint

%b() matches a note with any notes nested inside it. For whole words, put frontiers around the word, and compare lowercase text with a lowercase word. gsub returns the number of matches as its second value.

3. When a pattern needs alternation

A colleague’s Python script finds web requests in the log’s messages with this regular expression, which captures the method, the path, and the status code:

^(GET|POST|DELETE) (\S+) (\d{3})

It matches only the methods GET, POST, and DELETE, followed by a space, a path, a space, exactly three digits, and a space. Lua patterns have no | and no {3}.

Exercise L4.4 (LO-4.3, ★★, about 20 minutes)

Write request_of(message), which returns the method, the path, and the status as an integer for every message the regular expression matches, and nil for every other message.

Hint

Match the general shape, with the method captured as (%u+), and write \d{3} as three %ds. Then test the method against a set of the three allowed methods.

With parse_line and request_of done, this cell counts the requests in the log by status code. It is the whole log analysis in a few lines. It runs only once both exercises pass.

4. Building long strings

slow_report builds a text report by appending each line with ... The cell after it times the function on 2,500 to 20,000 rows, and prints how many times longer each row of the table took than the row above. Predict that ratio before you run it, from the reading. The timing cell takes about a second.

Exercise L4.5 (LO-4.4, ★, about 15 minutes)

Write fast_report(rows), which returns exactly the same string as slow_report(rows) but builds it with table.concat. The check compares the two on 1,000 rows, then times fast_report on 40,000 rows, which took slow_report about 3 seconds when this lab was tested.

5. UTF-8 text

Run the next cell, and compare each result with the reading’s section on UTF-8. Then change word to a word of your own with accented letters, or to an emoji, and run it again.

Exercise L4.6 (LO-4.4, ★★, about 20 minutes)

Write truncate(s, n), which shortens UTF-8 text for a preview. If s has at most n characters, it returns s. Otherwise it returns the first n characters followed by "…" (one character, U+2026). If s isn’t valid UTF-8, it returns nil and the position of the first invalid byte, as utf8.len does. It must never cut a character in half.

Hint

utf8.offset(s, n + 1) is the byte where character n + 1 starts, so the first n characters end one byte before it.

Summary

  • The string functions return new strings, count positions from 1 or, when negative, from the end, and can be called as methods.

  • One anchored pattern with captures parses a line of a log into its fields, and nil from match flags the lines that don’t fit.

  • %b() handles nested parentheses, and %f finds whole words, which regular expressions do with other tools.

  • A regular expression with alternation becomes a pattern for the general shape plus a test against a set.

  • .. in a loop grew about four times slower each time the input doubled; table.concat doesn’t.

  • #, upper, reverse, and %a work on bytes and ASCII; utf8.len, utf8.codes, and utf8.offset work on characters.

Next, do the Module 4 practice, then start PA2.