string: x11y22z33
I want to validate above value with string.match with 1 string and 2 numbers
string.match(s,"/^\s{1}\d{2}\s{1}\d{2}\s{1}\d{2}")
I tried but it didn't work
Lua
has a specific syntax for that:
string.match(s,"(%a)(%d%d)(%a)(%d%d)(%a)(%d%d)")
You can look in the manual in the chapter 5.4.1 – Patterns
Also string.find()
can handle patterns and gives you the position...
( :
means: The datatype "string" has string
metamethods )
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,tail,a,b,c
end
( Without errorhandling )
...to extract it with string.sub()
Output and result (return) is...
x11y22z33
26 34 x11 y22 z33
Above example also shows that the result of string.find()
is extended when ()
is used.
So the pattern (%a)(%d+)(%a)(%d+)(%a)(%d+)
resulting in 3 key/value pairs.
local head,tail,k1,x,k2,y,k3,z=str:find('(%a)(%d+)(%a)(%d+)(%a)(%d+)')
...
return head,tail,k1,x,k2,y,k3,z
-- Puts out: 26 34 x 11 y 22 z 33
-- And also works with x1024y3000z5