2016/02/26

Lua string.match vs string.gmatch

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 while match 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
>

Reference

  1. http://stackoverflow.com/questions/28593385/lua-string-match-vs-string-gmatch
  2. http://lua-users.org/wiki/StringLibraryTutorial

沒有留言:

張貼留言