blakem
blakem

Reputation: 11

Get last occurance of a Lua pattern with string.match

With Lua I am parsing the last occurrence of an XML tag from a large XML string using the pattern:

local firstPattern = "<tag>(.-)</tag>"

I then used the following code to find every occurrence:

local lastMatch
for match in string.gmatch(xmlString, firstPattern) do
  lastMatch = match
end

It did not seem very fast so I then tried adding a greedy character to the beginning of my pattern:

local secondPattern = ".*<tag>(.-)</tag>"
lastMatch = string.match(xmlString, secondPattern)

Printing os.clock() before and after the parsing I found the second pattern to be slightly faster but I have to think there is a better pattern to match the last occurrence of the xml tag.

I have also tried a third pattern but it only returns the first instance of the xml tag.

local thirdPattern = "<tag>(.-)</tag>.-$"
local firstMatch = string.match(xmlString, thirdPattern)

Upvotes: 1

Views: 2178

Answers (0)

Related Questions