The biggest difference is that string.match does a single match of "pattern" in "string" and you either have to repeat the variable definition and pattern xx times to get xx items parsed, or use an initial string.gsub in order to get a "count" of the items and do the string.match in a loop adding the length of the previous search as a starting index to the next. A bit ponderous either way.
With string.gmatch, the search for "pattern" in "string" is automatically done using an "iterator" that will handle much of the extra work involved with string.match.
Example:
Code: Select all
s = '<item><title>First</title><pubdate>Monday</pubdate></item><item><title>Second</title><pubdate>Tuesday</pubdate></item><item><title>Third</title><pubdate>Wednesday</pubdate></item><title>Forth</title><pubdate>Thursday</pubdate></item>'
count = 3
-- Using string.match
titlesm = {}
pubdatesm = {}
titlesm[1], pubdatesm[1], titlesm[2], pubdatesm[2], titlesm[3], pubdatesm[3] = string.match(s, '<item><title>(.-)</title><pubdate>(.-)</pubdate></item><item><title>(.-)</title><pubdate>(.-)</pubdate></item><item><title>(.-)</title><pubdate>(.-)</pubdate></item>')
for i = 1, count do
print('match: '..i..' of '..count, titlesm[i], pubdatesm[i])
end
-- Using string.gmatch
titlesg = {}
pubdatesg = {}
for sg1, sg2 in string.gmatch(s, '<item><title>(.-)</title><pubdate>(.-)</pubdate></item>') do
table.insert(titlesg, sg1)
table.insert(pubdatesg, sg2)
end
for i = 1, count do
print('gmatch: '..i..' of '..count, titlesg[i], pubdatesg[i])
end
http://lua-users.org/wiki/StringLibraryTutorial