Lua pattern for guid
Asked Answered
O

1

7

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.

Occupancy answered 11/4, 2014 at 13:27 Comment(0)
V
13

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, '%-')
Vollmer answered 11/4, 2014 at 13:45 Comment(4)
Thanks :). I have used above code and its works perfect.Occupancy
x = "%x"; pattern = { x:rep(8), x:rep(4), x:rep(4), x:rep(4), x:rep(12) }; pattern = table.concat(pattern, '-')Stingaree
@Stingaree I thought about string.rep(), but it doesn't look clean to me, using a table to build this pattern is smart, adding it to the answer.Vollmer
@hjpotter92, beware to escape - in a pattern.Quadrant

© 2022 - 2024 — McMap. All rights reserved.