Lua Pattern Frontiers
A frontier is a pattern piece that matches an empty position between two characters, not a character itself. It lets a pattern require a change of character kind at a spot, without consuming any text.
A frontier marks a word start position
The match is empty, so find returns start 1 and end 0 for the very first position.
local s, e = string.find("hello world", "%f[%w]")
print(s, e)A frontier also marks a word end position
Here the empty match sits between the last letter of hello and the space.
local s, e = string.find("hello world", "%f[%W]")
print(s, e)A frontier plus a class grabs a word start letter
The frontier fixes the position, and the class takes the first letter of the word.
print(string.match("hello world", "%f[%w]%w"))
print(string.match("hello world", "%f[%w]%w", 2))Example
local first = string.match("a cat sat", "%f[%w]%w%w%w")
print(first)
local second = string.match("a cat sat", "%f[%w]%w%w%w", 6)
print(second)Key points
- Frontier: %f[set] matches the empty position where the character before is outside the set and the character after is inside it.
- Word start: %f[%w] matches the empty position just before a word character that follows a non-word character.
- Word end: %f[%W] matches the empty position just after a word character that is followed by a non-word character.
- No consumption: a frontier adds no characters to the match, so the matched text starts at the frontier position.
- Use string.find with a frontier to get the position of the empty match, where the end position is one before the start position.
In this example, the frontier finds the start of a word and three word classes take its three letters, which gives cat. Searching again from position 6 skips past cat, so the same pattern gives sat instead.
Note
a frontier on its own matches an empty string, so pair it with a character class to capture real text.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does %f[%w] match in "hello world"?