On 12/15/2012 1:12 AM, Andre Caldas wrote:
Hi!
I have to use pattern matching in lua. I tried the function "string.gmatch".
I want to match (iterate over) strings of the type
([0-9]+)(-([0-9]*))?(,|$)
For example:
1,3- (iterations: 1 and 3-)
1-3,6,7 (iterations: 1-3 then 6 then 7)
1-2,5-6,10- (iterations 1-2 then 5-6 then 10-)
function whatever(str,n,action)
action = action or print
for s in string.gmatch(str,"[^,]+") do
local a, b, c = string.match(s,"^(%d+)(%-?)(%d-)$")
if c ~= "" then
for i=tonumber(a),tonumber(c) do
action(i)
end
elseif b ~= "" then
for i=tonumber(a),n or tonumber(a) do
action(i)
end
elseif a then
action(tonumber(a))
end
end
end
whatever("1,3-",5,function(i) print(">>>",i) end)
whatever("1-3,6,7")
whatever("1-2,5-6,10-",30)
-----------------------------------------------------------------
Hans Hagen | PRAGMA ADE
Ridderstraat 27 | 8061 GH Hasselt | The Netherlands
tel: 038 477 53 69 | voip: 087 875 68 74 | www.pragma-ade.com
| www.pragma-pod.nl
-----------------------------------------------------------------
___________________________________________________________________________________
If your question is of interest to others as well, please add an entry to the
Wiki!
maillist : ntg-context@ntg.nl / http://www.ntg.nl/mailman/listinfo/ntg-context
webpage : http://www.pragma-ade.nl / http://tex.aanhet.net
archive : http://foundry.supelec.fr/projects/contextrev/
wiki : http://contextgarden.net
___________________________________________________________________________________