2015-12-23 34 views
1

我需要在我正在編寫的程序中迭代一些字符串對。而不是把字符串對中大的一個表中,表,我把他們都在一個單一的字符串,因爲我覺得最終的結果是更易於閱讀:我可以創建一個返回可變數值的gmatch模式嗎?

function two_column_data(data) 
    return data:gmatch('%s*([^%s]+)%s+([^%s]+)%s*\n') 
end 

for a, b in two_column_data [[ 
    Hello world 
    Olá hugomg 
]] do 
    print(a .. ", " .. b .. "!") 
end 

輸出,你會想到什麼:

Hello, world! 
Olá, hugomg! 

然而,正如其名稱所示,該two_column_data功能只有在有兩個數據的確切列的作品。我怎樣才能使它適用於任何數量的列?

for x in any_column_data [[ 
    qwe 
    asd 
]] do 
    print(x) 
end 

for x,y,z in any_column_data [[ 
    qwe rty uio 
    asd dfg hjk 
]] do 
    print(x,y,z) 
end 

如果必要,我可以使用lpeg來完成此任務。

+0

'函數k_column_data(K,數據) 返回數據:gmatch(( '%S *(%S +)'):代表(k))的 end' –

+0

@葉戈爾我認爲重點是他不知道嗷嗷什麼「K」將 – warspyking

+0

OP,我認爲這應該工作:第一捕獲每個整條生產線,然後捕捉每一個字,把話說在一個表中,並解壓縮在返回 – warspyking

回答

1

這裏是RE版的LPEG

function re_column_data(subj) 
    local t, i = re.compile([[ 
      record <- {| ({| [ %t]* field ([ %t]+ field)* |} (%nl/!.))* |} 
      field <- escaped/nonescaped 
      nonescaped <- { [^ %t"%nl]+ } 
      escaped <- '"' {~ ([^"]/'""' -> '"')* ~} '"']], { t = '\t' }):match(subj) 
    return function() 
     local ret 
     i, ret = next(t, i) 
     if i then 
      return unpack(ret) 
     end 
    end 
end 

它basicly是CSV樣品的重做,並支持引述了一些不錯的使用情況字段:用空格值,空值(「」) ,多線值等

for a, b, c in re_column_data([[ 
    Hello world "test 
test" 
    Olá "hug omg" 
""]].."\tempty a") do 
    print(a .. ", " .. b .. "! " .. (c or '')) 
end 
2
function any_column_data(data) 
    local f = data:gmatch'%S[^\r\n]+' 
    return 
    function() 
     local line = f() 
     if line then 
     local row, ctr = line:gsub('%s*(%S+)','%1 ') 
     return row:match(('(.-) '):rep(ctr)) 
     end 
    end 
end 
+0

勺子餵養...再次... – warspyking

+0

這將返回一個最終的零,零對用於OP輸入 – wqw

+0

@wqw - 它似乎需要[工作](https://eval.in/493736)。請發佈錯誤行爲的代碼。 –

1
local function any_column_data(str) 
    local pos = 0 
    return function() 
     local _, to, line = str:find("([^\n]+)\n", pos) 
     if line then 
      pos = to 
      local words = {} 
      line:gsub("[^%s]+", function(word) 
       table.insert(words, word) 
      end) 
      return table.unpack(words) 
     end 
    end 
end 
+0

勺餵養警報 – warspyking

+2

@warspyking,抱怨...再次... – marsgpl

+0

抱怨?你不想讓這個人瞭解他的代碼中有什麼嗎? – warspyking

1

外環返回線,並且內部循環管線返回的話。

s = [[ 
    qwe rty uio 
    asd dfg hjk 
]] 

for s in s:gmatch('(.-)\n') do 
    for s in s:gmatch('%w+') do 
    io.write(s,' ') 
    end 
    io.write('\n') 
end 
+0

單獨的代碼塊並不能提供很好的答案。請添加解釋。 –

+0

除非代碼(如本例中)對於初學者程序員來說是不言而喻的。否則,我將不得不用計算機科學教授我給出的每個答案。 :) – tonypdmtr

+0

也許給你和提問者。但請記住,你並不孤單。只是解釋爲什麼你的答案解決了問題,錯誤在哪裏,你用什麼來解決問題等等......我建議你仔細閱讀http://stackoverflow.com/help/how-to-answer。 –

相關問題