我正试图在Lua中拆分此语句
sendex,000D6F0011BA2D60,fb,btn,1,on,100,null
我需要这样的输出:
Mac:000D6F0011BA2D60
Value:1
command:on
value:100
如何拆分并获取值?
答案 0 :(得分:1)
local input = "sendex,000D6F0011BA2D60,fb,btn,1,on,100,null"
local buffer = {}
for word in input:gmatch('[^,]+') do
table.insert(buffer, word)
--print(word) -- uncomment this to see the words as they are being matched ;)
end
print("Mac:"..buffer[2])
print("Value:"..buffer[5])
...
有关string.gmatch
功能的完整说明,请参见Lua reference。总而言之,它遍历一个字符串并搜索一个模式,在这种情况下为[^,]+
,这意味着不是逗号的1个或多个字符的所有组。每次找到所述模式时,它都会对其进行操作并继续搜索。
答案 1 :(得分:1)
如果您输入的内容与您描述的完全相同,则以下代码有效:
s="sendex,000D6F0011BA2D60,fb,btn,1,on,100,null"
Mac,Value,command,value = s:match(".-,(.-),.-,.-,(.-),(.-),(.-),")
print(Mac,Value,command,value)
它使用非贪婪模式.-
将输入分成多个字段。它还捕获了相关字段。