我按以下格式获取字符串:
abc:321,cba:doodoo,hello:world,eat:mysh0rts
我想从字符串中抓取一个数据配对实例并将其从字符串中删除,例如,如果我想抓住hello:world
之后的值,我希望这样:< / p>
local helloValue, remainingString = GetValue("hello")
world
将为hellovalue
返回abc:321,cba:doodoo,eat:mysh0rts
,remainingString
将返回{{1}}。
我使用循环这样做很麻烦,这样做会更好吗?
答案 0 :(得分:2)
这是一种方式:
local str = 'abc:321,cba:doodoo,hello:world,eat:mysh0rts'
local t = {}
for k, v in str:gmatch('(%w+):(%w+)') do
if k ~= 'hello' then
table.insert(t, k .. ':' .. v)
else
helloValue = v
end
end
remainingString = table.concat(t, ',')
print(helloValue, remainingString)
您可以自己将其转换为更一般的GetValue
功能。
答案 1 :(得分:1)
试试这个:
local str = 'abc:321,cba:doodoo,hello:world,eat:mysh0rts'
function GetValue(s,k)
local p=k..":([^,]+),?"
local a=s:match(p)
local b=s:gsub(p,"")
return a,b
end
print(GetValue(str,"hello"))
print(GetValue(str,"eat"))
如果要将整个字符串解析为键值对,请尝试:
for k,v in str:gmatch("(.-):([^,]+),?") do
print(k,v)
end
答案 2 :(得分:0)