Search code examples
xmlstringlualua-patterns

Finding the first string that matches a pattern in Lua (XML pattern matching)


I'm currently using the following code to parse a part of an Xml file (I first read the entire file into a single string).

for xmlMatch in xmlString:gmatch("<MyXmlElement.*</MyXmlElement>") do
    -- Do something.
end

The problem I have is that the for loop is only executing once because the the gmatch function is returning only a single string, which starts at the first instance of MyXmlElement and ends at the closure of the last instance of MyXmlElement. How can I parse the string so as the the pattern is matched whenever the string "</MyXmlElement>" is first found (and not the last case only)?


Solution

  • There are 3 things wrong here:

    • gmatch returns the captured substrings from the string, so you need to use () around stuff you want to use in the loop
    • for matching the least possible number of characters you should use .- as pattern to go just until the first possible </MyXmlElement>
    • and you need variables after the for (but I guess that's just a typo)

    So all together:

    for att,cont in XmlString:gmatch'<MyXmlElement%s*(.-)>(.-)</MyXmlElement>' do
        -- something
    end
    

    should do the trick.