Search code examples
regexluaguidlua-patterns

Lua pattern for guid


I am trying to implement a pattern in Lua but no success

The pattern I need is like regex: [a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}

which is to validate guid.

I am not able to find proper way to find the implement regex in Lua and not able to find in documentation also.

Please help me to implement above regex for guid.


Solution

  • You can use this:

    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))
    

    Note that:

    1. Modifier {8} is not supported in Lua pattern.
    2. - needs to be escaped with %-.
    3. Character class %x is equivalent to [0-9a-fA-F].

    A clear way to build the pattern using an auxiliary table, provided by @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, '%-')