Hello. I’m trying to make a module that turns something like
"3h 12m 5s"
to seconds
I know I’d have to check for \n, \t, and " "
, but how could I ignore all whitespace, and get the h, m, and s out of that?
Hello. I’m trying to make a module that turns something like
"3h 12m 5s"
to seconds
I know I’d have to check for \n, \t, and " "
, but how could I ignore all whitespace, and get the h, m, and s out of that?
You could use string patterns:
local Hour, Minute, Second = string.match("3h 12m 5s", "%s*(%d+)%s*[hH]%s*(%d%d?)%s*[mM]%s*(%d%d?)%s*[sS]%s*")
If you’re wonderin how this works in a nutshell, ()
are used for string captures in string patterns so what we do is we check for 3 1-2 digit numbers with %d%d?
and %d+
string patterns. %s*
s are used to make the string captures work even when there is whitespace is present.
Edit: Fixed some typos. I probably shouldn’t be answering posts at 1:30 AM.
local Hour, Minute, Second = string.match("3h 12m 5s", "%s*(%d+)%s*[hH]%s*(%d%d?)%s*[mM]%s*(%d%d?)%s*[sS]%s*")
print(Hour)
print(Minute)
print(Second)
I made a minor changes, I changed the first %d%d?
to %d+
mainly because hours shouldn’t be limited by 2 numbers unless we have a greater value then hours
also I removed “^” and “$” because stuff like “test 3h 12m 5s test” would not work due to the string not starting in a white space/number or ending in a white space/“s” or “S”
also one small thing you might want to change
you did local Hour, Second, Minute
instead of local Hour, Minute, Second
EDIT: edited my second paragraph
Thanks, by the way, %d*
wouldn’t work because that would still mach even when no number is provided for hour. It’s better to use %d+
for hour.
Still doesn’t change the fact that I shouldn’t be answering questions at 1:30 AM though.
yea you are right about that, good catch