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

时间:2014-12-03 05:47:21

标签: string lua string-formatting lua-patterns

我按以下格式获取字符串:

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

我想从字符串中抓取一个数据配对实例并将其从字符串中删除,例如,如果我想抓住hello:world之后的值,我希望这样:< / p>

local helloValue, remainingString = GetValue("hello")

world将为hellovalue返回abc:321,cba:doodoo,eat:mysh0rtsremainingString将返回{{1}}。

我使用循环这样做很麻烦,这样做会更好吗?

3 个答案:

答案 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)

(hello:[^,]+,)

只需替换empty string。替换数据和$1就是您想要的。请参阅演示。

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