3

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?

2
  • It's better to show what you are doing, so that we know how to improve. Commented Dec 3, 2014 at 6:06
  • What's your expected output, if the input is abc:321,cba:doodoo,eat:mysh0rts,hello:world ? Commented Dec 3, 2014 at 6:11

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try also this:

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"))

If you want to parse the whole string into key-value pairs, try this:

for k,v in str:gmatch("(.-):([^,]+),?") do
    print(k,v)
end

Comments

0
(hello:[^,]+,)

Just do a replace with empty string.The replace data and $1 are the things you want.See demo.

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

1 Comment

The question was mistakenly tagged with regex, Lua pattern isn't regular expression, so this won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.