2016-09-06 13 views

回答

1

(也許過於簡單化,如果是的話,對不起...)
如果你想在「=」打破你的文件中的行t時將它們分配爲重點,值對:

-- 
-- PART I - read from a file 
-- 
local file = "pattern.dat"      -- our data file 
local t = {}         -- hold file values 
for l in io.lines(file) do      -- get one line at a time 
    local k, v = string.match(l, "(.+)=(.+)") -- key, value delimited by '='' 
    t[k] = v         -- save in table 
    print(k,t[k]) 
end 

print("\n\n") 

-- 
-- PART II - read from data string 
-- 
local data = "[email protected]/ip=192.168.100.1/mac=af:45:t6:45:67" 
data = data .. "/"        -- need a trailing '/' 
t = {}           -- hold data values 
for l in string.gmatch(data, "(.-)/") do  -- get one 'line' at a time 
    local k,v = string.match(l, "(.+)=(.+)") -- key, value delimited by '='' 
    t[k] = v 
    print(k,t[k]) 
end 

注關於「^」錨(從參考手冊「gmatch」條目):

對於這個函數,在模式的開始插入符「^」不起作用作爲錨,如這會阻止迭代。 http://www.lua.org/manual/5.3/manual.html#pdf-string.gmatch

+0

你好,你幫了我很多!你的代碼完美工作,非常感謝! – user2530802

+0

喜聚隆實驗室, 在另一個場合,我將需要得到這個數據,否則例如: 數據=「[email protected]/id=13412513251315/mac=12:A4:67:89:FG/IP = 192.168.1.100「 而不是文件,數據是在一行中可以告訴我如何得到上面的代碼相同的結果? – user2530802

+0

請參閱上面代碼中的「第II部分」。 –

1

你實際上只獲得了一場比賽,因爲*是貪婪。如果您嘗試分割線,請嘗試(%w+)=([^'\n]*)\n

注意:Lua使用模式,而不是正則表達式。有時候,這種差異並不重要,有時甚至是至關重要的。

+0

感謝您的關注! – user2530802