使用string.match获取Lua模式的最后一个匹配项。

使用Lua,我正在使用以下模式从一个大 XML 字符串中解析最后一次出现的 XML 标记:

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

然后我使用以下代码找到每个出现:

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

它似乎不太快,所以我尝试在我的模式开头添加一个贪婪字符:

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

在解析前后打印 os.clock(),我发现第二个模式稍微更快,但我认为有更好的模式匹配 xml 标记的最后一次出现。

我还尝试了第三个模式,但它只返回 xml 标记的第一次出现。

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