1

i want grep the table and turn into array, but i dont know how to make it

excample data :

<table border class="stat"><tr><th>Estate</th><th>Cost</th><th>Income</th><th>Interest</th></tr><tr><td>Power Station</td><td>15 Bil</td><td>126.1 Mil</td><td><b>0.84%</b></td></tr><tr><td>Railway</td><td>25 Bil</td><td>216.2 Mil</td><td><b>0.86%</b></td></tr><tr><td>Military Base</td><td>50 Bil</td><td>434.4 Mil</td><td><b>0.87%</b></td></tr><tr><td>Toll Road</td><td>5 Bil</td><td>34.9 Mil</td><td><b>0.70%</b></td></tr><tr><td>Water Pump</td><td>10 Bil</td><td>77.5 Mil</td><td><b>0.78%</b></td></tr></table>

output data :

estate[1][1] = "Power Station"
estate[1][2] = "15 Bil"
estate[1][3] = "126.1 Mil"
estate[1][4] = "0.84%"

estate[2][1] = "Railway"
estate[2][2] = "25 Bil"
estate[2][3] = "216.2 Mil"
estate[2][4] = "0.86%"

1 Answer 1

2

Pattern matching is not the recommended tool for parsing HTML but in this case it works just fine.

The code below creates a table with named fields instead of numeric indices, which is probably more useful.

H=[[
<table border class="stat"><tr><th>Estate</th><th>Cost</th><th>Income</th><th>Interest</th></tr><tr><td>Power Station</td><td>15 Bil</td><td>126.1 Mil</td><td><b>0.84%</b></td></tr><tr><td>Railway</td><td>25 Bil</td><td>216.2 Mil</td><td><b>0.86%</b></td></tr><tr><td>Military Base</td><td>50 Bil</td><td>434.4 Mil</td><td><b>0.87%</b></td></tr><tr><td>Toll Road</td><td>5 Bil</td><td>34.9 Mil</td><td><b>0.70%</b></td></tr><tr><td>Water Pump</td><td>10 Bil</td><td>77.5 Mil</td><td><b>0.78%</b></td></tr></table>
]]

local name={}
local n=0
for h in H:gmatch("<th>(.-)</th>") do
    n=n+1
    name[n]=h
    --print(n,h)
end

local estate={}
local n=-1 -- skip th
for r in H:gmatch("<tr>(.-)</tr>") do
    n=n+1
    estate[n]={}
    local k=0
    for d in r:gmatch("<td>(.-)</td>") do
        k=k+1
        --print(n,k,d)
        if d:match("<b>") then d=r:match("<b>(.-)</b>") end
        estate[n][name[k]]=d
    end
end

for i=1,#estate do
    for k,v in pairs(estate[i]) do
        print(i,k,v)
    end
end
Sign up to request clarification or add additional context in comments.

Comments

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.