gpt4 book ai didi

arrays - 将 Lua string.match 输出存储到数组

转载 作者:行者123 更新时间:2023-12-02 09:48:32 24 4
gpt4 key购买 nike

通常我使用两个变量来存储类似这样的输出:

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”)和一个模式(在本例中为“警报牙医 (%w+) (%w+)”),并且如果找到则返回所需的伴随单词,否则返回“nil”。问题是该模式查找的单词数是未定义的。在本例中为 2,但我希望用户能够输入任何模式,即“警报牙医 (%w+) (%w+) (%w+) (%w+)”或“警报牙医 (%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 的未定义大小输出存储在一个数组中。

最佳答案

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

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

关于arrays - 将 Lua string.match 输出存储到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com