Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 544
James Bedford Avatar asked Dec 07 '25 06:12

James Bedford


1 Answers

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.

like image 105
jpjacobs Avatar answered Dec 09 '25 18:12

jpjacobs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!