Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
user3523906 Avatar asked Apr 11 '14 13:04

user3523906


People also ask

What is Lua pattern matching?

Lua patterns can match sequences of characters, where each character can be optional, or repeat multiple times. If you're used to other languages that have regular expressions to match text, remember that Lua's pattern matching is not the same: it's more limited, and has different syntax.

Does Lua support regex?

Unlike several other scripting languages, Lua does not use POSIX regular expressions (regexp) for pattern matching.


1 Answers

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, '%-')
like image 106
Yu Hao Avatar answered Oct 01 '22 06:10

Yu Hao