将Lua的string.match输出存储到数组中。

通常我用两个变量来存储这种情况的输出:

a = {'alarm boy car dentist','alarm car dentist elephant','alarm dentist elephant fabulous','alarm elephant fabulous goat'}
k, v = string.match(a[1], 'alarm dentist (%w+) (%w+)' )
print(k, v)
elephant fabulous

但是我想要将其存储在一个数组或表中,而不是使用两个变量。

我的最终目标是创建一个函数,其中我输入一个数组(在这种情况下是'a')和一个模式(在这种情况下是'alarm dentist (%w+) (%w+)'),它返回所找到的期望的附加单词或'nil'。问题在于,模式寻找的单词数是未定义的。在这种情况下是2,但我希望用户能够输入任何模式,例如'alarm dentist (%w+) (%w+) (%w+) (%w+)'或'alarm dentist (%w+)'。

因此,这是我的思路:(我使用Ubuntu 12.04LTS的命令行工具来测试它)

a = {'alarm boy car dentist','alarm car dentist elephant','alarm dentist elephant fabulous','alarm elephant fabulous goat'}
function parse_strings (array, pattern)
words = nil
for i=1, #array do
    c = string.match(array[i], pattern)
    if c ~= nil then
        words = c
        end
    end
    return words
end
print (parse_strings (a, 'alarm dentist (%w+) (%w+)'))
elephant

但是,只有第一个值存储在“c”中,而不是c[1]='elephant'和c[2]='fabulous'。

最坏的情况是我可以查找模式寻找的单词数,但我仍然需要找到一种方法将string.match的未定义大小的输出存储在一个数组中。

点赞
用户33252
用户33252

由于你的模式中有两个捕获,所以你需要为 match 函数使用两个结果变量。尝试如下代码:

words = nil
for i=1, #array do
    c,d = string.match(array[i], pattern)
    if c ~= nil then
        words = {c,d}
        return words
    end
end

这将返回...

> for k,v in ipairs(words) do print (k,v) end
1   elephant
2   fabulous
2014-05-21 22:58:07
用户1009479
用户1009479

你可以将结果存储到表中:

local t = {string.match(array[i], pattern)}
if #t ~= 0 then
    words = t
    end
end

现在,parse_string 的返回值为一个表:

local result =  (parse_strings (a, 'alarm dentist (%w+) (%w+)'))
for k, v in ipairs(result) do
    print(k, v)
end
2014-05-22 01:12:26