use*_*563 4 arrays string lua lua-patterns
通常,我使用两个变量来存储类似以下内容的输出:
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
Run Code Online (Sandbox Code Playgroud)
但我不想使用两个变量,而是将其存储在数组或表中。
我的最终目标是创建一个函数,在该函数中输入数组(在此例中为“ a”)和模式(在此例中为“ alarm dentist(%w +)(%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
Run Code Online (Sandbox Code Playgroud)
但只有第一个值存储在“ c”中,而不是c [1] ='elephant'和c [2] ='fabulous'。
最坏的情况是,我可以搜索模式搜索的单词数,但仍然需要找到一种方法来存储string.match一个数组中未定义大小的输出。
您可以将结果存储到表中:
local t = {string.match(array[i], pattern)}
if #t ~= 0 then
words = t
end
end
Run Code Online (Sandbox Code Playgroud)
现在的返回值parse_string是一个表:
local result = (parse_strings (a, 'alarm dentist (%w+) (%w+)'))
for k, v in ipairs(result) do
print(k, v)
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2140 次 |
| 最近记录: |