Search code examples
regexluanumberslua-patterns

tonumber and regex


Given is a (time-value) String like:

local dt = "12:34:56"

I want to cut this string into

hh, mm, ss = "12", "34", "56"

therefore I use regex like this:

local hh = string.format("%02d", tonumber( dt:gsub(":..:..","") ))
local mm = string.format("%02d", tonumber( dt:gsub(":..:",""):gsub(":","") ))
local ss = string.format("%02d", tonumber( dt:gsub("..:..:","") ))

which works fine. ( The time string is coming from userinput, so I fill it with 0 if user writes "1" instead of "01")

But in cases where the value starts with 0, it is getting out of range for luas tonumber() (Signed zero I guess), same with "1", tonumber() seems to not handle values below "2") Could anyone tell me how to handle this situation?

Beside this, I would be happy if you could show me the bad practice in my regex, if there's some.


Solution

  • The whole thing can be shortened to this one liner:

    local hh, mm, ss = dt:match "(%d%d?):(%d%d?):(%d%d?)"
    

    As for the error occuring in your tonumber, it is because gsub returns 2 values after its operation. First being the substituted sring and the second being a number. tonumber assumes the second argument to be the base provided (which would be 1 I think). Since numbers with base 1 can only be 0; it raises an error.