I need to come up with a pattern to match YYYY-MM-DDTHH:MM:SS.s+Z
with the milliseconds part being optional. The regex is simple and looks like this:
^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?Z$
Which match these strings:
"2022-04-02T11:24:59Z"
"2022-04-02T11:24:59.123Z"
In Lua, this isn't as straight forward as I thought. I've tried a couple of patterns but ultimately only got this one to work:
local pat3 = "^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%d[%.%d+]*Z$"
local dt1 = "2022-04-02T11:24:59Z"
local dt2 = "2022-04-02T11:24:59.123Z"
local dt_invalid = "2022-04-02T11:24:59.123.000.000Z"
print(dt1:match(pat3))
print(dt2:match(pat3))
print(dt_invalid:match(pat3))
That pattern meets most of my needs, but it's bothering me that strings like dt_invalid
match too. I've also tried the following patterns with no success:
local pat1 = "^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%d[%.%d+]?Z$"
local pat2 = "^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%d(%.%d+)?Z$"
Lua has a simplified pattern matching functionality, but these patterns look more like the regex pattern. I'm not knowledgeable enough in Lua to know the difference or what I'm missing. Why does pat1
and pat2
not work? Is there a better pattern than pat3
?