Skip to content

Regex

The Regex library provides regular expression functionality for Lua, allowing pattern matching and string manipulation using regular expressions.

Regex.new(pattern)

Creates a new regex object with the given pattern.

local regex = Regex.new("\\d+")

Returns a regex object. If the pattern is invalid, the regex object will be created but marked as invalid (see Status method).

Regex.Escape(str)

Escapes special regex characters in a string.

local escaped = Regex.Escape("(Hello)")
-- escaped is now "\(Hello\)"

Returns the escaped string.

Regex Object Methods

regex:Status()

Checks the validity of the regex pattern.

local regex = Regex.new("\\d+")
local valid, error = regex:Status()
if valid then
    print("Regex is valid")
else
    print("Regex is invalid: " .. error)
end

Returns two values: 1. A boolean indicating if the regex is valid 2. An error message string (empty if valid)

regex:Match(str)

Finds all matches of the regex pattern in the given string.

local regex = Regex.new("\\d+")
local matches = regex:Match("There are 123 apples and 456 oranges")
for i, match in ipairs(matches) do
    print(i, match)
end

Returns a table of all matches found in the string.

regex:Replace(str, replacement)

Replaces the first occurrence of the regex pattern in the string with the replacement string.

local regex = Regex.new("\\d+")
local result = regex:Replace("There are 123 apples", "many")
-- result is now "There are many apples"

Returns the modified string with the first match replaced.

Examples

Validating an email address

local email_regex = Regex.new("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$")
local valid, _ = email_regex:Status()
if valid then
    local is_valid = #email_regex:Match("[email protected]") > 0
    print("Is valid email:", is_valid)
else
    print("Invalid regex pattern")
end

Extracting numbers from a string

local number_regex = Regex.new("\\d+")
local text = "The price is $15.99 for 3 items"
local numbers = number_regex:Match(text)
for _, number in ipairs(numbers) do
    print("Found number:", number)
end

Replacing sensitive information

local ssn_regex = Regex.new("\\d{3}-\\d{2}-\\d{4}")
local text = "My SSN is 123-45-6789"
local redacted = ssn_regex:Replace(text, "XXX-XX-XXXX")
print(redacted)  -- Outputs: My SSN is XXX-XX-XXXX