-1

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

SweetNGX
  • 153
  • 1
  • 9

2 Answers2

3

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

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

Robert
  • 2,711
  • 7
  • 15
1

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
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15