2

I have the following string

abc=1.2;bcd=2.4;xyz=10.9

I want to split it into the following table

{ {"abc", "1.2}, {"bcd", "2.4"}, {"xyz", "10.9"} }

I am currently doing this by splitting the strings first by ; and then by =.

In PHP I can use the following preg_match pattern to do this in a single step without iteration. Is it possible to do this in Lua?

preg_match_all("/(?:([a-z]+)=([0-9.]+)(?:;|$))/", $a, $match, PREG_SET_ORDER);

1 Answer 1

2

Try this:

s="abc=1.2;bcd=2.4;xyz=10.9"

s=s..";"
t={}
for k,v in s:gmatch("(.-)=(.-);") do
    t[#t+1]={k,v}
end
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. This is much better than my current solution.
Currently I am using table.insert(t, {k, v}). Is t[#t+1]={k,v} preferred over table.insert?
@JoyceBabu, table.insert is fine.

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.