Hello!
On Mon, Nov 25, 2013 at 1:41 PM, ankit wrote:
> Not sure what is causing the difference here. Ideally #match should have
> returned 0 in both the cases as # should not work for non-consecutive array
> tables.
> Can you please help in understanding this difference?
Both results are valid because you have a nil hole in the middle.
According to the Lua 5.1 reference manual, "If the array has 'holes'
(that is, nil values between other non-nil values), then #t can be any
of the indices that directly precedes a nil value (that is, it may
consider any such nil value as the end of the array)." See
http://www.lua.org/manual/5.1/manual.html#2.5.5
> Also is using
> the next function the best way of finding out whether the regex matched any
> one of the groups or not? (don't want to run for loop).
>
In your particular case, just test the match return value directly:
if match then
end
Only when one of the regex groups is matched, the whole match is
successful. If you want to test a particular submatch is matched, just
test the corresponding field directly, as in
if match[1] then
-- submatch 1 is matched
end
if match[2] then
-- submatch 2 is matched
end
If you're writing a general regex API wrapper that want to check which
regex in a regex list is matched (first), then ngx.re.match is not
really the right API for this task. I'm going to add a specific API
for this usage, that is,
local captures, regex_id, err = ngx.re.match_multi(subj, {re1,
re2, ...}, opts)
where it returns the captures for the matched regex only in the regex
list re1, re2, ..., as well as the index for the matched regex in the
list (lua table).
Similarly, we can also have an ngx.re.find_multi which only returns
the beginning and end index for the matched substring (no submatch
support).
Best regards,
-agentzh