1
votes

I'm trying to parse a text, and based on tags to do actions.

The text is:

<window>
    <caption>My window
</window>
<panel>
    <label>
        <caption>
        <position>50,50
        <color>255,255,255
    </label>
</panel>

Code:

function parse_tag(chunck)
    for start_tag,tag_name in string.gfind(chunck,"(<(.-)>)") do
        if (child_obj[tag_name]) then
            print(start_tag)
            for data,end_tag in string.gfind(chunck,"<" .. tag_name ..">(.-)(</" .. tag_name ..">)") do
                for object_prop,value in string.gfind(data,"<(.-)>(.-)") do
                    print("setting property = \"" .. object_prop .. "\", value of" .. value);
                end
            end
            print("</" .. tag_name ..">");
        elseif(findInArray(main_obj,tag_name)) then
            print("Invalid data");
            stop();
        end
    end
end
for key,tag in ipairs(main_obj) do
    for start_tag,tag_name,chunck,end_tag in string.gfind(data,"(<(" .. tag.name .. ")>)(.-)(</" .. tag.name .. ">)") do --> searching for window/panel start and end tags
        if (findInArray(main_obj,tag_name)) then
            print(start_tag)
            parse_tag(chunck); --> parses the tag with child tag
            print(end_tag)
        end
    end
end

It seems to fail getting the value, as I get the following output:

<window>
</window>
<panel>
<label>
setting property = "caption", value of
setting property = "position", value of
setting property = "color", value of
</label>
</panel>

How can I use match the string after the first <%tag%> until the next <%tag%> or end of the chunk.

2
This generally seems to be a bad idea, why not use an XML parser? - legends2k

2 Answers

1
votes
string.gfind(data,"<(.-)>(.-)")

Here, you try to match the value with .-. However, - is lazy, i.e, .- will try to match as little as possible, in this case, an empty string.

Try telling it to match until the next <:

string.gfind(data,"<(.-)>(._)<")
0
votes

Tried different type of captures. This

string.gfind(data,"<(.-)>([^%<+.-%>+]+)")

Seems to work