Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first instance of a pattern in Lua and remove it from string

I get strings in the following format:

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

I'd like to grab one instance of the data pairing from the string and remove it from the string, so for example if I wanted to grab the value following hello:world I'd like this to happen:

local helloValue, remainingString = GetValue("hello")

Which will return world for hellovalue and abc:321,cba:doodoo,eat:mysh0rts for remainingString.

I'm doing this rather cumbersomely with loops, what would a better way of doing it be?

like image 254
meds Avatar asked Dec 18 '25 05:12

meds


1 Answers

This is one way:

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)

You can turn this to a more general GetValue function yourself.

like image 171
Yu Hao Avatar answered Dec 20 '25 00:12

Yu Hao