2

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]

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
IgorKushnir
  • 89
  • 2
  • 8

4 Answers4

3

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.

Piglet
  • 27,501
  • 3
  • 20
  • 43
Bohemian
  • 412,405
  • 93
  • 575
  • 722
3

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)
Piglet
  • 27,501
  • 3
  • 20
  • 43
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

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

koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15
  • 1
    This pattern will match say "000 1 234" which may not be what the OP wants. – lhf Dec 06 '21 at 10:35
  • Yes. Personally i like to match those MAC from output where hex is separated with ```:``` like the output from ```ifconfig``` do. And with a simple change it matches for IPv6' - MAC: ```('%x+%:+%x+'):rep(5)``` IPv6: ```('%x+%:+%x+'):rep(4)``` – koyaanisqatsi Dec 07 '21 at 10:42
0

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)
IgorKushnir
  • 89
  • 2
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 06 '21 at 18:30