Lua模式排除

我有一个预定义的代码,例如“12-345-6789”,希望使用 Lua 模式匹配第一个和最后一个部分,例如“12-6789”。排除第二个数字集和连字符应该可以工作,但我用模式一直无法理解或确认它是否可行。

我知道我可以像这样分别捕获每个数字:

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

并使用它,但这需要我重写很多代码。我理想情况下想采取当前的模式匹配表,并将其添加为与 string.match 一起使用。

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

你不能用单个捕获实现这个功能,但将两个捕获结果拼接在一起非常简单:

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

如果你正在尝试对一组模式进行匹配,那么最好将其重构为一组函数的列表:

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
2014-11-21 20:45:45
用户5096048
用户5096048

虽然这个帖子很旧,但仍有人可能会发现这有用。

如果你只需要中间由连字符隔开的第一个和最后一个数字集合,你可以使用 string.gsub。

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

通过使用模式的第一个和第二个匹配,它将简单地返回字符串 "12-6789"。

2017-06-06 11:30:15