JackRazors
JackRazors

Reputation: 33

Parsing key value pair with Lua

I am trying to parse key=value pairs with Lua. An example string looks like:

str="a=b b=c name=george jetson name2=paul davidson company=radioshack"
for name, value in string.gfind(str, "([^&=]+)=([^&=]+)") do
     print(name)
     print(value)
end

result:

a
b b
c name
george jetson name2
paul davidson company
radioshack

Unfortunately its grabbing the next key and adding it to the value which I don't want. What am I missing?

Upvotes: 3

Views: 1608

Answers (1)

lhf
lhf

Reputation: 72312

You need to treat spaces in values and spaces before keys differently.
The code below is one way of doing it.

str="a=b b=c name=george jetson name2=paul davidson company=radioshack"    
str=" "..str.."\n"
str=str:gsub("%s(%S-)=","\n%1=")
for name, value in string.gmatch(str, "(%S-)=(.-)\n") do
     print(name,"'"..value.."'")
end

Upvotes: 4

Related Questions