2014-05-21 34 views
3

通常,我用兩個變量來的東西輸出存儲這樣的:商店的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')和一個模式(這種情況是'警報牙醫(%w +)(%w +)')和它返回所需的伴隨詞/ s,否則返回'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] ='大象'和c [2] ='神話般'。

最壞的情況我可以搜索模式搜索的詞數,但我仍然需要找到一種方法將string.match中未定義的大小輸出存儲在一個數組中。

回答

3

您可以將結果保存到一個表:

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 
+0

爲什麼不使用'{string.match(whatever)}'而不是'table.pack(string.match(whatever))'? –

+0

@NiccoloM。你是對的,我正在過度思考。我已經修改它使用表構造函數。謝謝。 –

+0

非常感謝,工作。 – user3325563

0

由於您的模式中有兩個捕獲,因此您需要兩個結果變量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 
+0

謝謝,道格。 是的,這是我通常這樣做的,但這裏的問題是未定義的單詞數量(它可以是1,2,3,...),但上面的解決方案解決了這個問題。 – user3325563