LUA 字符串短语匹配

问题描述

字符串:x11y22z33

我想用 string.match 和 1 个字符串和 2 个数字验证上面的值

string.match(s,"/^\s{1}\d{2}\s{1}\d{2}\s{1}\d{2}")

我试过了,没用

解决方法

Lua 有一个特定的语法:

string.match(s,"(%a)(%d%d)(%a)(%d%d)(%a)(%d%d)")

您可以查看手册中的5.4.1 – Patterns章节

http://www.lua.org/manual/5.1/manual.html

,

还有 string.find() 可以处理模式并为您提供位置...
: 表示:数据类型“字符串”具有 string 元方法)

do
local str='not important important: x11y22z33 and ignore rest'
local head,tail,a,b,c=str:find('(%a%d%d)(%a%d%d)(%a%d%d)')

print(str:sub(head,tail))

return head,c
end

(没有错误处理)
...使用 string.sub()
提取它 输出和结果(返回)是...

x11y22z33
26  34  x11 y22 z33

上面的例子还表明,当使用 string.find() 时,() 的结果被扩展了。
所以模式 (%a)(%d+)(%a)(%d+)(%a)(%d+) 产生了 3 个键/值对。

local head,k1,x,k2,y,k3,z=str:find('(%a)(%d+)(%a)(%d+)(%a)(%d+)')
...
return head,z 
-- Puts out: 26 34 x 11 y 22 z 33
-- And also works with x1024y3000z5