Lua Pattern Exclusion

2.6k views Asked by At

I have a predefined code, e.g."12-345-6789", and wish to match the first and last portions with Lua patterns, e.g. "12-6789". An exclusion of the second number set and the hyphen should work but I am having trouble figuring that out with patterns or if it is possible.

I know I could capture each individually like so

code = "12-345-6789"
first, middle, last = string.match(code, "(%d+)-(%d+)-(%d+)")

and use that but it would require a lot of code rewriting on my part. I would ideally like to take the current table of pattern matches and add it to be used with string.match

lcPart = { "^(%d+)", "^(%d+%-%d+)", "(%d+)$", ?new pattern here? }
code = "12-345-6789"
newCode = string.match(code, lcPart[4])
2

There are 2 answers

0
Colonel Thirty Two On

You can't do this with one capture, but it's trivial to splice the results of two captures together:

local first, last = string.match(code, "(%d+)%-%d+%-(%d+)")
local newid = first .. "-" .. last

If you're trying to match against a list of patterns, it may be better to refactor it into a list of functions instead:

local matchers = {
    function(s) return string.match(s, "^(%d+)") end,
    function(s) return string.match(s, "^(%d+%-%d+)") end,
    -- ...
    function(s)
        local first, last = string.match(code, "(%d+)%-%d+%-(%d+)")
        return first .. "-" .. last
    end,
}

for _,matcher in ipairs(matcher) do
    local match = matcher(code)
    if match then
        -- do something
    end
end
0
ViBo On

I know this is an old thread, but someone might still find this useful.

If you need only the first and last sets of digits, separated by a hyphen you could use string.gsub for that

local code = "12-345-6789"
local result = string.gsub(code, "(%d+)%-%d+%-(%d+)", "%1-%2")

This will simply return the string "12-6789" by using the first and second captures from the pattern.