【问题标题】:Lua pattern for guid用于指导的 Lua 模式
【发布时间】:2014-05-25 16:34:30
【问题描述】:

我正在尝试在 Lua 中实现一个模式但没有成功

我需要的模式就像正则表达式:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}

这是为了验证guid

我无法找到在 Lua 中找到实现正则表达式的正确方法,也无法在文档中找到。

请帮助我为 guid 实施上述正则表达式。

【问题讨论】:

    标签: regex lua guid lua-patterns


    【解决方案1】:

    你可以用这个:

    local pattern = "%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x"
    local guid = "3F2504E0-4F89-41D3-9A0C-0305E82C3301"
    print(guid:match(pattern))
    

    注意:

    1. Lua 模式不支持修饰符 {8}
    2. - 需要用 %- 转义。
    3. 字符类%x等价于[0-9a-fA-F]

    使用辅助表构建模式的清晰方法,由@hjpotter92 提供:

    local x = "%x"
    local t = { x:rep(8), x:rep(4), x:rep(4), x:rep(4), x:rep(12) }
    local pattern = table.concat(t, '%-')
    

    【讨论】:

    • 谢谢:)。我已经使用了上面的代码,它的工作很完美。
    • x = "%x"; pattern = { x:rep(8), x:rep(4), x:rep(4), x:rep(4), x:rep(12) }; pattern = table.concat(pattern, '-')
    • @hjpotter92 我想到了string.rep(),但对我来说看起来并不干净,使用表格构建这种模式很聪明,将其添加到答案中。
    • @hjpotter92,注意以模式转义-
    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 2011-04-07
    • 2016-10-21
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多