IgorKushnir
IgorKushnir

Reputation: 89

Repetitive regular expression in Lua

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]

Upvotes: 2

Views: 613

Answers (4)

IgorKushnir
IgorKushnir

Reputation: 89

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)

Upvotes: 0

Bohemian
Bohemian

Reputation: 425428

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.

Upvotes: 3

koyaanisqatsi
koyaanisqatsi

Reputation: 2823

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

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)

Upvotes: 3

Related Questions