【问题标题】:Lua Pattern ExclusionLua 模式排除
【发布时间】:2014-11-21 20:42:40
【问题描述】:

我有一个预定义的代码,例如"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])

【问题讨论】:

  • 你能列出你想要匹配的可接受的字符串吗?

标签: string lua lua-patterns


【解决方案1】:

你不能用一个捕获来做到这一点,但是将两个捕获的结果拼接在一起是微不足道的:

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

【讨论】:

    【解决方案2】:

    我知道这是一个旧线程,但有人可能仍然觉得这很有用。

    如果您只需要第一组和最后一组数字,用连字符分隔,您可以使用 string.gsub 来表示

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

    这将通过使用模式中的第一个和第二个捕获简单地返回字符串“12-6789”。

    【讨论】:

      猜你喜欢
      • 2015-02-02
      • 2012-09-06
      • 2021-12-25
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      相关资源
      最近更新 更多