Lua 中的重复正则表达式

我需要找到一个包含 6 对十六进制数(不含 0x)的模式,例如“00 5a 4f 23 aa 89”

这个模式对我来说是可行的,但问题是是否有简化的方法?

[%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]

原文链接 https://stackoverflow.com/questions/70242040

点赞
stackoverflow用户256196
stackoverflow用户256196

Lua支持十六进制数字%x(参见https://www.lua.org/pil/20.2.html),因此您可以将所有[%da-f]替换为%x

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

Lua不支持特定的量化符号{n}。如果支持的话,可以使它变得更短。

2021-12-06 07:54:35
stackoverflow用户3832970
stackoverflow用户3832970

Lua patterns不支持限定符,而正则表达式支持更多的功能(因此,Lua patterns甚至不是正则表达式)。

由于您知道需要重复模式的一部分多少次,因此可以动态构建模式:

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

请参见Lua示例

'[%da-f][%da-f]'..('%s[%da-f][%da-f]'):rep(5)可以进一步缩短为%x十六进制字符简写:

'%x%x'..('%s%x%x'):rep(5)
2021-12-06 08:32:32
stackoverflow用户11740758
stackoverflow用户11740758

你也可以使用加号加上“一个或多个”来简化...

print(('Your MAC is: 00 5a 4f 23 aa 89'):match('%x+%s%x+%s%x+%s%x+%s%x+%s%x+'))
-- 在Lua 5.1到5.4中测试

它在“Pattern Item:”下描述...

https://www.lua.org/manual/5.4/manual.html#6.4.1

2021-12-06 09:47:56
stackoverflow用户3495395
stackoverflow用户3495395

最终解决方案:

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

local answer = text:match(pattern)
print (answer)
2021-12-06 16:01:52