在Lua中查找模式的第一个实例并将其从字符串中删除。

我获得以下格式的字符串:

abc:321,cba:doodoo,hello:world,eat:mysh0rts

我想从字符串中获取一组数据配对并将其从字符串中删除,例如,如果我想获取hello:world之后的值,则会发生以下情况:

local helloValue, remainingString = GetValue("hello")

这将返回hellovalueworldremainingStringabc:321,cba:doodoo,eat:mysh0rts

我用循环做了这件事情,这样做有什么更好的方法吗?

点赞
用户3679490
用户3679490
(hello:[^,]+,)

只需使用“空字符串”进行替换。替换数据和 $1 是你想要的。请参见演示。

http://regex101.com/r/yR3mM3/24

2014-12-03 05:51:31
用户1009479
用户1009479

这是一种方法:

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函数。

2014-12-03 06:14:35
用户107090
用户107090

也可以尝试这个:

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
2014-12-03 10:28:54