String 在Lua中找到模式的第一个实例,并将其从字符串中删除
我得到以下格式的字符串:String 在Lua中找到模式的第一个实例,并将其从字符串中删除,string,lua,string-formatting,lua-patterns,String,Lua,String Formatting,Lua Patterns,我得到以下格式的字符串: abc:321,cba:doodoo,hello:world,eat:mysh0rts 我想从字符串中获取数据配对的一个实例,并将其从字符串中删除,因此,例如,如果我想获取以下值hello:world,我希望这样做: local helloValue, remainingString = GetValue("hello") 对于hellovalue和abc:321,cba:doodoo,eat:mysh0rts的remainingString,它将返回world 我
abc:321,cba:doodoo,hello:world,eat:mysh0rts
我想从字符串中获取数据配对的一个实例,并将其从字符串中删除,因此,例如,如果我想获取以下值hello:world
,我希望这样做:
local helloValue, remainingString = GetValue("hello")
对于hellovalue
和abc:321,cba:doodoo,eat:mysh0rts
的remainingString
,它将返回world
我用循环做这件事相当麻烦,有什么更好的方法
(hello:[^,]+,)
只需用空字符串替换即可。替换数据和$1
就是您想要的。请参阅演示
这是一种方法:
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
函数。也可以尝试以下操作:
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
最好显示您正在做什么,以便我们知道如何改进。如果输入是abc:321,cba:doodoo,eat:mysh0rts,hello:world
,那么您的预期输出是什么?问题被错误地标记为regex,Lua模式不是正则表达式,所以这不起作用。