Overview
Just now, I spent a while on coding with string.gmatch and string.match. In my opinion, they are not quite intuitive for their usage. So, I tried to placed my example here for future references.
Code example
gmatch
aims for global search whilematch
ends at 1st match.
> line = "Jan 1 08:17:02 ABC hotplug: [OK] ifup: 'lan' => 'br-lan'"
> pat = '([^ ]+)'
# End at Jan
> return line:match('([^ ]+)')
Jan
# Equivalent to split by ' '
> for w in line:gmatch(pat) do print(w) end
Jan
1
08:17:02
ABC
hotplug:
[OK]
ifup:
'lan'
=>
'br-lan'
gmatch
does not good at dealing with^
> line = "Jan 1 08:17:02 ABC hotplug: [OK] ifup: 'lan' => 'br-lan'"
> pat = '^([A-Z][a-z][a-z])'
# Able to get Jan
> =line:match(pat)
Jan
# Unable to get anything
> for w in line:gmatch(pat) do print(w) end
>