Repetitive regular expression in Lua

Viewed 149

I need to find a pattern of 6 pairs of hexadecimal numbers (without 0x), eg. "00 5a 4f 23 aa 89"

This pattern works for me, but the question is if there any way to simplify it?

[%da-f][%da-f]%s[%da-f][%da-f]%s[%da-f][%da-f]%s[%da-f][%da-f]%s[%da-f][%da-f]%s[%da-f][%da-f]

4 Answers

Lua supports %x for hexadecimal digits, so you can replace all every [%da-f] with %x:

%x%x%s%x%x%s%x%x%s%x%x%s%x%x%s%x%x

Lua doesn't support specific quantifiers {n}. If it did, you could make it quite a lot shorter.

Lua patterns do not support limiting quantifiers and many more features that regular expressions support (hence, Lua patterns are not even regular expressions).

You can build the pattern dynamically since you know how many times you need to repeat a part of a pattern:

local text = '00 5a 4f 23 aa 89'
local answer = text:match('[%da-f][%da-f]'..('%s[%da-f][%da-f]'):rep(5) )
print (answer)
-- => 00 5a 4f 23 aa 89

See the Lua demo.

The '[%da-f][%da-f]'..('%s[%da-f][%da-f]'):rep(5) can be further shortened with %x hex char shorthand:

'%x%x'..('%s%x%x'):rep(5)

Also you can use a "One or more" with the Plus-Sign to shorten up...

print(('Your MAC is: 00 5a 4f 23 aa 89'):match('%x+%s%x+%s%x+%s%x+%s%x+%s%x+'))
-- Tested in Lua 5.1 up to 5.4

It is described under "Pattern Item:" in...
https://www.lua.org/manual/5.4/manual.html#6.4.1

final solution:

local text = '00 5a 4f 23 aa 89'
local pattern = '%x%x'..('%s%x%x'):rep(5)

local answer = text:match(pattern)
print (answer)
Related