Regular Expressions in Lua

Our first example demonstrates how to work with regular expressions in Lua. We’ll use the lrexlib library, which provides PCRE (Perl Compatible Regular Expressions) support.

local rex = require "rex_pcre"

-- This tests whether a pattern matches a string.
local match = rex.match("peach", "p([a-z]+)ch")
print(match and "true" or "false")

-- We'll use this pattern for the following examples
local pattern = "p([a-z]+)ch"

-- This finds the match for the regexp.
local match = rex.match("peach punch", pattern)
print(match)

-- This finds the first match but returns the
-- start and end indexes for the match instead of the
-- matching text.
local start, finish = rex.find("peach punch", pattern)
print("idx:", start, finish)

-- The gsub function can be used to replace
-- subsets of strings with other values.
local result = rex.gsub("a peach", pattern, "<fruit>")
print(result)

-- The gmatch function can be used to iterate over
-- all matches in a string.
for match in rex.gmatch("peach punch pinch", pattern) do
    print(match)
end

-- We can use a function to transform matched text
local result = rex.gsub("a peach", pattern, function(match)
    return match:upper()
end)
print(result)

To run the program, save it as regular_expressions.lua and use the Lua interpreter:

$ lua regular_expressions.lua
true
peach
idx: 1   5
a <fruit>
peach
punch
pinch
a PEACH

This example demonstrates basic usage of regular expressions in Lua using the lrexlib library. It covers pattern matching, finding matches, replacing text, and iterating over matches.

Note that Lua doesn’t have built-in regular expression support like some other languages. The lrexlib library provides this functionality, but it needs to be installed separately.

For more advanced usage and a complete reference on Lua regular expressions with lrexlib, check the library’s documentation.